Posts Tagged ‘json’

Alright, this time I decided to talk a little bit about JSON and AJAX calls. Think about a scenario where you do not want the page to post back and you want  to get some Data from Database would work but how there are lot of times we mess our head finding this out and yet no solution…chill, following will take you through on how to load data Asynchronously or Synchronously :

  • First things first, lets create a Simple ASP.NET Application and remove everything except the new Scripts folder that gets created in new template of Visual Studio 2010.
  • Make sure the jQuery files are there
  • Add a new asp.net page and add jQuery references to the page as below:
  • jquery_reference

    jquery_reference

  • Add a Method in your Code behind to call the Business Logic in JSON Format, something like below, for this example I am adding it in the same aspx page’s code behind:
[WebMethod]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public static string GetJSONData()
    {
        //Call your Business Logic
        BusinessDataClass objBDC = new BusinessDataClass();
        //Call the Method that returns Data in JSON string
        return objBDC.GetDataInJSON();
    }
  • Now the main part comes into picture, which is calling the above mentioned method using jQuery and Ajax, come to your aspx page and under the head section code the following script, right below jquery references:
 <script type="text/javascript">
       $(function getData() {
           $.ajax({
               type: "POST",
               url: "GetData.aspx/GetJSONData",               
               contentType: "application/json; charset=utf-8",
               dataType: "json",  
               success: function (data) {
                   alert(data.d);
               }
           });
       });
    </script>

The main this to see here is the attributes that we are using while making an Ajax call under  the getData function:

  1. url :A string containing the URL to which the request is sent. In our example we are calling the method “GetJSONData” from the page “GetData.aspx”, following is how the GetJSONData method looks like:
 [WebMethod]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public static string GetJSONData()
    {
        //Call your Business Logic
        BusinessDataClass objBDC = new BusinessDataClass();

        //Call the Method that returns Data in JSON string
        return objBDC.GetDataInJSON();
    }
  1. type, Default: ‘GET’ The type of request to make (“POST” or “GET”), default is “GET”. Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
  2. dataType, Default: Intelligent Guess (xml, json, script, or html). The type of data that you’re expecting back from the server.

Run your app and you will see the Ajax request being server , to see more about it open the Developer toolbar and start capturing the network and you will see the type of data being sent across. Here’s a quick screen shot:

Developer Toolbar Capture

Developer Toolbar Capture

Hope the post would help you learn little about jSON and Ajax requests.

Advertisements

Web API : ASP.NET has introduced a new concept of building Web API on top of .NET Framework and as we all know HTTP services has a vast market in terms of clients including browsers, mobile phones or any desktop application, in this blog we are going to talk a bit about what ASP.NET WebAPI is all about and how to make one and consume one:

First you would need the following:

  1. Visual Studio 2011 or Visual Studio 2010 with SP1
  2. ASP.NET MVC 4 (how to get that is mentioned Below)

Steps to get MVC 4 and Web API:

    1. Go and download ASP.NET MVC 4 from ( http://go.microsoft.com/fwlink/?LinkId=243392 )
    2. Once Downloaded and Installed you will see following Template installed in your New Project Dialog box:

MVC 4 Project Template

  1. After you select your project MVC 4 you will get New ASP.NET MVC 4 Project Dialog from there choose “Web API” type project:

    Web API Dialog

    Web API Dialog

Create a New Model:

A model is nothing but an object to represent data in your project. A model is automatically serialized by ASP.NET web API into JSON or XML or any other format that can be read by a client (Browser or phone or any other client). So first to see how Web API works we will add a new Model by adding a new class to Models folder in your solution explorer:

Add a Model

Add a Model

Give some meaningful name to your model for example “Employee” and set some properties like EmployeeID, Name etc :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebAPI.Models
{
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }        
    }
}

Adding a New Controller:

A Controller is nothing but an object that a Client Calls using HTTP requests, By default when you create a MVC 4 project there will be two controllers created already “HomeController” and “ValueController”, if you are familiar with MVC 3 then you know HomeController is meant to serve HTML pages for application or site where as the “ValueController” is a sample WebAPI controller created by MVC 4 Project template for reference and inherits the ApiController class, we will leave this as it is and create a New Controller of type API in the Controllers folder by right clicking and adding a new Empty API Controller and name is “EmployeeController”:

Add a Controller

Add a Controller

Empty API Controller

Empty API Controller

Once added add using Statement to call your Models in EmployeeController:

using WebAPI.Models;

And add the following code to return a default list of Employee and a Controller Method to search your list as given below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    public class EmployeeController : ApiController
    {
      public IEnumerable<Employee> GetAllEmployees()
      {
          return new List<Employee>
          {
              new Employee() { EmployeeID = 1, EmployeeName = "brainz 1"},
              new Employee() { EmployeeID = 2, EmployeeName = "brainz 2"},
              new Employee() { EmployeeID = 3, EmployeeName = "brainz 3"}
          };
      }

        public Employee GetEmployeeById(int id)
        {
            if (id < 1 || id > 3)
            {
                throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
            }
            return new Employee() { EmployeeID = id, EmployeeName="brainz "+ id.ToString() };
        }
    }
}

The GetAllEmployee Method would return list of employee and GetEmployeeById will return the employee with matching ID,else httpResponseException will be thrown(this is nothing but a 404 Error), once done compile this and your Web API is ready to be used and consumed.

Calling the API using JQuery or JavaScript:

Go to View by Expanding the Views folder and open Index.cshtml file, and remove everything by the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>ASP.NET Web API</title>
    <script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>   
</head>
<body>
    <div>
        <h1>All Employees</h1>
        <ul id='employee' />
    </div>
    <div>
        <label for="EmployeeID">ID:</label>
        <input type="text" id="EmployeeID" size="5"/>
        <input type="button" value="Search" onclick="find();" />
        <p id="Employee" />
    </div>
</body>
</html>

Once done let’s call a HTTP GET Request to request the api: api/employee, using the getJSON function by making an Ajax Call:

<script type="text/javascript">
        $(document).ready(function () {
            // Send an AJAX request
            $.getJSON("api/employee/",
            function (data) {
                // On success, 'data' contains a list of employees.
                $.each(data, function (key, val) {                    
                    // Format the text to display.
                    var str = val.EmployeeID + ': ' + val.EmployeeName;

                    // Add a list item for the Employee.
                    $('<li/>', { html: str }).appendTo($('#employee'));
                });
            });
        });

    </script>

The final index.cshtml would look like :

<!DOCTYPE html>
<html lang="en">
<head>
    <title>ASP.NET Web API</title>
    <script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            // Send an AJAX request
            $.getJSON("api/employee/",
            function (data) {
                // On success, 'data' contains a list of employees.
                $.each(data, function (key, val) {                    
                    // Format the text to display.
                    var str = val.EmployeeID + ': ' + val.EmployeeName;

                    // Add a list item for the Employee.
                    $('<li/>', { html: str }).appendTo($('#employee'));
                });
            });
        });

        function find() {
            var id = $('#EmployeeID').val();
            $.getJSON("api/employee/" + id,
        function (data) {
            var str = data.EmployeeID + ': ' + data.EmployeeName;
            $('#employee').html(str);
        })
    .fail(
        function (jqXHR, textStatus, err) {
            $('#employee').html('Error: ' + err);
        });
        }        
    </script>
</head>
<body>
    <div>
        <h1>All Employees</h1>
        <ul id='employee' />
    </div>
    <div>
        <label for="EmployeeID">ID:</label>
        <input type="text" id="EmployeeID" size="5"/>
        <input type="button" value="Search" onclick="find();" />
        <p id="Employee" />
    </div>
</body>
</html>

Once this is done run your application to see the result and don’t forget to put your comments if any

Output

Output

Note: CSHTML page usually uses Razor but we have used simple HTML in our case.