AJAX-Enabled WCF Service Using JSON

Introduction

 
This article explains the use of JSON in WCF and AJAX-enabled WCF services.
 
Description
 
WCF is capable of sending messages in XML format or JSON formats. JSON format has a much more compact presentation than XML and is highly used today in web applications that use AJAX asynchronous style of communications. Each of WCF's message formats is independent of the response. WCF message has two properties.
  1. RequestFormat
  2. ResponseFormat
webmessageformat 
 
WebMessageFormat.Json specifies that the message response format we want is JSON. By default it is XML. We can integrate AJAX-enabled services via JSON.
 
JSON
 
The JavaScript Object Notation (JSON) format is suitable for creating JavaScript objects. Today most of the browser-based application WCF services can be consumed by JavaScript or jQuery. WCF must send the response in JSON object. To establish the communication between JavaScript or jQuery and the service we mainly use JSON. It helps in data serialization and deserialization. We can configure this setting in WebGet or WebInvoke attribute. In JSON one does not need to create lengthy tags like XML, hence it is lighter than XML. It is language-independent and produces clean and readable data.
 

AJAX enabled WCF Service

 
This is a service that can be called from an ajax client-side script. It returns JSON wrapped objects to the browser through a JavaScript call. Here we don't need the code behind to call it. That means we can call the WCF directly instead of having to go to the WebFrom.aspx.cs or VB code behind file to make the call to the WCF Web service.
 
Let's see a demo of this type of service and compare this with a WCF REST service.
 
Step 1
 
asp dot net web form application 
 
Open Visual Studio 2012 then select "File" -> "New" -> "Project...". We will then get the following Image. From the template choose Visual C# then choose Web. Then select the ASP.NET Web Forms Application. Let's give the project the name AjaxEnabledWCFDemo, then click the OK button to go to the next step.
 
Step 2
 
Right-click on the project and click on the add new item. We will get the following image. Then choose Web then choose AJAX -enabled WCF Service. Then provide the name to your service. I have given it the name AjaxService.svc. Then click the Add button.
 
ajax enable wcf service 
 
Step 3
 
If we look into the References then we can see that System.ServiceModel is automatically added to the project. In the AjaxService.svc class I will add a class Student. I want to send the list of this class to the client side.
 
This is my class.
  1. public class Student  
  2. {  
  3.       public int Id { getset; }  
  4.       public string Name { getset; }  
  5.       public int Mark { getset; }  
  6.       public string Grade { getset; }  
  7. }  
I will write the following function that will send the student details in the form of a list to the client side.
  1. /// <summary>  
  2. /// This function returns the list of student data.  
  3. /// </summary>  
  4. /// <returns></returns>  
  5.         [OperationContract]  
  6.         [WebInvoke(Method = "GET",  
  7.             BodyStyle = WebMessageBodyStyle.WrappedRequest,  
  8.             ResponseFormat = WebMessageFormat.Json  
  9.          )]  
  10.         public List<Student> getStudentData()  
  11.         {  
  12.             try  
  13.             {  
  14.                 List<Student> lstStudent = new List<Student>();  
  15.   
  16.                 Student oStudent = new Student();  
  17.                 oStudent.Id = 1;  
  18.                 oStudent.Name = "Shashank";  
  19.                 oStudent.Mark = 100;  
  20.                 oStudent.Grade = "O";  
  21.                 lstStudent.Add(oStudent);  
  22.   
  23.                 Student oStudent1 = new Student();  
  24.                 oStudent1.Id = 2;  
  25.                 oStudent1.Name = "Syam";  
  26.                 oStudent1.Mark = 90;  
  27.                 oStudent1.Grade = "A";  
  28.                 lstStudent.Add(oStudent1);  
  29.   
  30.                 Student oStudent2 = new Student();  
  31.                 oStudent2.Id = 3;  
  32.                 oStudent2.Name = "Ram";  
  33.                 oStudent2.Mark = 80;  
  34.                 oStudent2.Grade = "B";  
  35.                 lstStudent.Add(oStudent2);  
  36.                 return lstStudent;  
  37.             }  
  38.             catch (Exception ex)  
  39.             {  
  40.                 throw new FaultException<string>  
  41.                 (ex.Message);    
  42.             }  
  43.   
  44.         }  
In the preceding function, I have used the WebInvoke attribute. The ResponseFormat is JSON.
 
Step 4
 
In the Default.aspx page, I have added the following code snippets. I am calling the ajax-enabled service from the UI using jQuery. I am binding the student data in a HTML table.
  1. <asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">  
  2.     <script src="Scripts/jquery-1.8.2.min.js"></script>  
  3.     <script type="text/javascript" >  
  4.         $(document).ready(function () {             
  5.             $.ajax({  
  6.                 url: "/AjaxService.svc/getStudentData",  
  7.                 dataType: "json",  
  8.                 type: "GET",                
  9.                 contentType: "application/json; charset=utf-8",  
  10.                 success: function (data) {  
  11.                     if (data.d != null) {  
  12.                         var dtStudent = data.d;                         
  13.                         var html = "<table style='width:50%' align='center' bgcolor='#FFFF' border=1><th>ID</th><th>Name</th><th>Mark</th><th>Grade</th>";  
  14.                         for (i = 0; i < dtStudent.length; i++)  
  15.                         {  
  16.                             html += "<tr><td>" + dtStudent[i].Id + "</td><td>" + dtStudent[i].Name + "</td><td>" + dtStudent[i].Mark + "</td><td>" + dtStudent[i].Grade + "</td></tr>";  
  17.                         }                      
  18.                         html += "</table>";  
  19.                         $("#divStudent").html(html);  
  20.                     }  
  21.                 },  
  22.                 error: function (d) {  
  23.                     alert("Error");  
  24.                 }  
  25.             });  
  26.         });  
  27.     </script>  
  28. </asp:Content>  
  29. <asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">  
  30.    <div id="divStudent"></div>  
  31. </asp:Content>  
Note : Let's look into the web config file.
  1. <system.serviceModel>  
  2.     <behaviors>  
  3.       <endpointBehaviors>  
  4.         <behavior name="AjaxEnabledWCFDemo.AjaxServiceAspNetAjaxBehavior">  
  5.           <enableWebScript />  
  6.         </behavior>  
  7.       </endpointBehaviors>  
  8.     </behaviors>  
  9.     <serviceHostingEnvironment aspNetCompatibilityEnabled="true"  
  10.       multipleSiteBindingsEnabled="true" />  
  11.     <services>  
  12.       <service name="AjaxEnabledWCFDemo.AjaxService">  
  13.         <endpoint address="" behaviorConfiguration="AjaxEnabledWCFDemo.AjaxServiceAspNetAjaxBehavior"  
  14.           binding="webHttpBinding" contract="AjaxEnabledWCFDemo.AjaxService" />  
  15.       </service>  
  16.     </services>  
  17.   </system.serviceModel>  
We need the end point and set the service behavior in the config file. While we have done the REST demo, I have added the end point behaviors manually in the config file. But if we are using the ajax-enabled services then the code above is automatically added to the config file. It is an advantage of ajax-enabled services over REST services.
 
Step 5
 
As I have called the service in the document.ready of the Default page, when we browse the page we will get the following result.
 
called the servive 
 
I hope this was informative.
 


Similar Articles