23 February 2011

How To Process JSON With C# and JQuery

JavaScript Object Notation affectionately known as JSON is a wonderful way to deliver content to the browser in a lightweight method that can both save on bandwidth and reduce page weight.

Following example contain 3 sections
1.Call a Asp.net server method using using jQuery
2.Return the Employees as a JSON data.
3.Display the Data in a standard HTML table.

Steps

1.Make a Class Employee

   1: public class ClsEmployee
   2: {    
   3:     public string PropPubStrFirstName
   4:     {    get;    set;    }
   5:  
   6:     public string PropPubStrLastName
   7:     {    get;    set;    }
   8:  
   9:     public string PropPubStrMiddleName
  10:     {    get;    set;    }
  11:  
  12:     public Employee(string StrPriFirstName, string StrPriMiddleName, string StrPriLastName)
  13:     {
  14:         PropPubStrFirstName= StrPriFirstName
  15:         PropPubStrMiddleName= StrPriMiddleName
  16:         PropPubStrLastName= StrPriLastName
  17:     }
  18: }    

2.Now create a web method in your code behind file as



   1:  
   2: [WebMethod]
   3: public static List GetEmployees()
   4: {
   5:     const string query = "SELECT [FirstName], [MiddleName], [LastName] FROM TblEmployee";
   6:     DataTable dt = BuildDataTable(query);
   7:     List empList = null;
   8:  
   9:     if (dt != null)
  10:     {
  11:         empList = new List();
  12:  
  13:         for (int i = 0; i < dt.Rows.Count; i++)
  14:         {
  15:         empList.Add(new Employee(dt.Rows[i]["FirstName"].ToString(),
  16:         dt.Rows[i]["MiddleName"].ToString(),
  17:         dt.Rows[i]["LastName"].ToString()));
  18:         }
  19:     }
  20:  
  21:     return empList;
  22: }
  23:  
  24:  
  25: public static DataTable BuildDataTable(string query)
  26: {
  27:     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionstring"].ConnectionString);
  28:     SqlDataAdapter ada = new SqlDataAdapter(query, con);
  29:     DataTable dt = new DataTable();
  30:     ada.Fill(dt);
  31:     return dt;
  32: }

3.Write a jQuery Function to get and show the data in a table.



   1: <script type="text/javascript">// <![CDATA[
   2: $(document).ready
   3: (
   4:     function() 
   5:     {
   6:         $.ajax
   7:         (
   8:             {
   9:                 type: "POST",
  10:                 url: "Default.aspx/GetTopTenEmployees",
  11:                 contentType: "application/json; charset=utf-8",
  12:                 dataType: "json",
  13:                 success: function(msg) 
  14:                 {
  15:                     BuildTable(msg.d);
  16:                 }
  17:             }
  18:         );
  19:     }
  20: );
  21:  
  22: function BuildTable(msg) 
  23: {
  24:     var table = '
  25:     <table>
  26:     <thead>
  27:     <tr>
  28:     <th>First Name</th>
  29:     <th>Middle Name</th>
  30:     <th>Last Name</th>
  31:     </thead>
  32:     <tbody>';
  33:     for (var i = 0, l = msg.length; i < l; i++)
  34:     {
  35:         var person = msg[i];
  36:         var row = '
  37:         <tr>';
  38:         row += '
  39:         <td>' + person.FirstName + '</td>';
  40:         row += '
  41:         <td>' + person.MiddleName + '</td>';
  42:         row += '<td>' + person.LastName + '</td>';
  43:         row += '</tr>';
  44:         table += row;
  45:     }
  46:     table += '</tbody></table>';
  47:     $('#Container').html(table);
  48: }
  49: </script>
  50: <div id="Container">

You can use HTTP Snipper to see the contents being returned..It will be as follows


{"d":[{"__type":"Employee","FirstName":"Gustavo","LastName":"Achong","MiddleName":""},{"__type":"Employee","FirstName":"Catherine","LastName":"Abel","MiddleName":"R."},{"__type":"Employee","FirstName":"Kim","LastName":"Abercrombie","MiddleName":""},{"__type":"Employee","FirstName":"Humberto","LastName":"Acevedo","MiddleName":""},{"__type":"Employee","FirstName":"Pilar","LastName":"Ackerman","MiddleName":""},{"__type":"Employee","FirstName":"Frances","LastName":"Adams","MiddleName":"B."},{"__type":"Employee","FirstName":"Margaret","LastName":"Smith","MiddleName":"J."},{"__type":"Employee","FirstName":"Carla","LastName":"Adams","MiddleName":"J."},{"__type":"Employee","FirstName":"Jay","LastName":"Adams","MiddleName":""},{"__type":"Employee","FirstName":"Ronald","LastName":"Adina","MiddleName":"L."}]}


As you can see we have the type of the Employee object along with the properties and values


5 comments:

  1. Could u plz explain what does "msg" mean in following lines

    success: function(msg)
    {
    BuildTable(msg.d);
    }

    Can u plz mail me a demo of this.......

    ReplyDelete
  2. pinks..msg is the value, you will return from your server side Code

    ReplyDelete
  3. HI sukesh

    How to get response from web-service using jquery. i need to display that response as auto-complete for text box in asp.net MVC 3.

    http://secure.intravel.ca/POC/WebServices/FlightsWS.asmx .. this is the web-service that i m using.. i m trying for AirportList method.

    ReplyDelete
  4. you can use the the same $.ajax method in jQuery

    ReplyDelete

Your comments, Feedbacks and Suggestions are very much valuable to me :)

Things are upgraded

My Dear readers, I am really thankful for being supportive all these years. This site was the first blog site I ever created in my life...