Ajax Enabled WCF Service

Background

This article explains the Ajax Enabled WCF service to create an Ajax Enabled WCF service. Visual Studio provides by default a template for that. So let us learn step-by-step about the Ajax Enabled WCF service so beginners also can understand. 
 
Requirements to understand this tutorial 
 
If you are a beginner and need to understand what a WCF service is, refer to the following article of mine:
  1. Creating WCF Service

I hope you read it if you are unfamiliar with WCF services, so I will briefly define what a WCF service.

Windows Communication Foundation (WCF)
 
WCF is a library for applications of various platforms or the same platform to communicate over the various protocols such as TCP, HTTP, HTTPS and so on.

Now the next requirement is for you to at least be aware of Ajax. If you are unfamiliar with Ajax then please refer to the following article of mine:

I hope you have read it. Now let us see about Ajax Enabled WCF Services.

What is Ajax Enabled Services?

An Ajax Enabled Service is a template in Visual Studio that provides a configuration by default to consume a WCF service using Ajax and jQuery. So let us demonstrate this concept with a web application. 

Step 1
 
Create a WCF Service as in the following:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".

  2. "File" - "New WebSite" - "C#" - "ASP.NET Empty Web Application" (to avoid adding a master page).

  3. Provide the web site a name such as "AjaxEnabledWCFServiceApplication" or another as you wish and specify the location.

  4. Then right-click on Solution Explorer - "Add New Item". You will see the Ajax Enabled WCF service template as same as the following image,

ajax enable wcf service

Now click on "Add". The Solution Explorer will then look as in the following:
 
 
 
Step 2

Add a web page to the new web application as in the following:
  1. Right-click on Solution Explorer then select "Add New Item". You will see the Web Form  template then click on Add.

  2. Now drag and drop one Input Button, a Text Box to the Default.aspx Page. Then the source code of the Default.aspx page will look as follows:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title></title>  
  7.     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  8.     
  9.   
  10. </head>  
  11. <body bgcolor="black">  
  12.     <form id="form1" runat="server">  
  13.     <br />      
  14.     <br />      
  15.     <br />    
  16.     <table style="color: White;">  
  17.         <tr>  
  18.             <td>  
  19.                 Enter Number  
  20.             </td>  
  21.             <td>  
  22.                 <input type="text" id="txtgetMulti" />  
  23.             </td>  
  24.         </tr>  
  25.         <tr>  
  26.             <td>  
  27.             </td>  
  28.             <td>  
  29.                 <input id="btnGetMulti" type="button" value="Get Result" />  
  30.             </td>  
  31.         </tr>  
  32.     </table>  
  33.       
  34.     </form>  
  35. </body>  
  36. </html> 
Step 3

Create a method in the Service.svc file as in the following:
  1. public class Service  
  2. {  
  3.    
  4.         [OperationContract]  
  5.         [System.ServiceModel.Web.WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]  
  6.         public int Multiplication(int Number)
  7.         {  
  8.             return Number*Number;  
  9.   
  10.         }  

 Step 4


To allow calling a WCF service from JavaScript, jQuery or ScriptManager, we need to add the following line at the top of the class name. We also need to specify the namespace. The namespace may be any name used to uniquely identify the service as in the following:
  1. [ServiceContract(Namespace = "Multiplication")]  
  2.  [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)] 
After adding the preceding line, the Service class will look as follows:
  1. [ServiceContract(Namespace = "Multiplication")]  
  2. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
  3. public class Service  
  4. {  
  5.    
  6.         [OperationContract]  
  7.         [System.ServiceModel.Web.WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]  
  8.         public int Multiplication(int Number)  
  9.         {  
  10.             return Number*Number;  
  11.   
  12.         }  

Step 5

Let us see the UI of the .aspx page:
 
 
In the preceding UI you saw that there is a TextBox that accepts integer type numbers and there is the Get Result HTML button that calls the jQuery function to call the WCF  Method.
 
Step 6

Refer to the jQuery library script Path file as in the following:
  1. <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> 
 Now see the  the Web.config file configuration as follows:
  1. <system.serviceModel>  
  2.     <behaviors>  
  3.       <endpointBehaviors>  
  4.         <behavior name="ServiceAspNetAjaxBehavior">  
  5.           <enableWebScript/>  
  6.         </behavior>  
  7.       </endpointBehaviors>  
  8.     </behaviors>  
  9.     <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>  
  10.     <services>  
  11.       <service name="Service">  
  12.         <endpoint address="" behaviorConfiguration="ServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="Service"/>  
  13.       </service>  
  14.     </services>  
  15.   </system.serviceModel> 
Step 7

Create a jQuery function to call the service method using JSON as in the following:
  1. $("#btnGetMulti").live("click"function () {  
  2.             $.ajax({  
  3.                 type: "POST",  
  4.                 contentType: "application/json; charset=utf-8",  
  5.                 url: 'Service.svc/GetMultiplication',  
  6.                 data: '{"Number": "' + $("#txtgetMulti").val() + '"}',  
  7.                 processData: true,  
  8.                 dataType: "json",  
  9.                 success: function (response) {  
  10.                       
  11.                     alert(response.d);  
  12.                 },  
  13.                 error: function (errormsg)   
  14.                 {  
  15.                     alert(errormsg.responseText);  
  16.                 }  
  17.             });  
  18.         }); 
In the preceding function we are ing the input value to the server method using JSON and displaying the response in an alert box. The entire source code will look as follows:
 
 Default.aspx
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title></title>  
  7.     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
  8.     <script type="text/javascript">  
  9.         $("#btnGetMulti").live("click"function () {  
  10.             $.ajax({  
  11.                 type: "POST",  
  12.                 contentType: "application/json; charset=utf-8",  
  13.                 url: 'Service.svc/GetMultiplication',  
  14.                 data: '{"Number": "' + $("#txtgetMulti").val() + '"}',  
  15.                 processData: true,  
  16.                 dataType: "json",  
  17.                 success: function (response) {  
  18.                       
  19.                     alert(response.d);  
  20.                 },  
  21.                 error: function (errormsg)   
  22.                 {  
  23.                     alert(errormsg.responseText);  
  24.                 }  
  25.             });  
  26.         });  
  27.     </script>  
  28.   
  29. </head>  
  30. <body bgcolor="black">  
  31.     <form id="form1" runat="server">  
  32.     <br />      
  33.     <br />      
  34.     <br />    
  35.     <table style="color: White;">  
  36.         <tr>  
  37.             <td>  
  38.                 Enter Number  
  39.             </td>  
  40.             <td>  
  41.                 <input type="text" id="txtgetMulti" />  
  42.             </td>  
  43.         </tr>  
  44.         <tr>  
  45.             <td>  
  46.             </td>  
  47.             <td>  
  48.                 <input id="btnGetMulti" type="button" value="Get Result" />  
  49.             </td>  
  50.         </tr>  
  51.     </table>  
  52.       
  53.     </form>  
  54. </body>  
  55. </html> 
 Service.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Activation;  
  7. using System.ServiceModel.Web;  
  8. using System.Text;  
  9.   
  10. [ServiceContract(Namespace = "Multiplication")]  
  11. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
  12. public class Service  
  13. {  
  14.    
  15.         [OperationContract]  
  16.         [System.ServiceModel.Web.WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]  
  17.         public int GetMultiplication(int  Number)  
  18.         {  
  19.             return Number*Number;  
  20.   
  21.         }  

Now click F5 to run the application. Enter a number into the TextBox and click on the Get Result button, it will show the following output:
 
 
 
In the preceding image the output is returned from the WCF service as 1000.
Notes
  • For detailed code please download the Zip file attached above.
  • Don't forget to refer to the jQuery Script file Reference.
Summary

From all the examples above we have learned what an Ajax Enabled WCF service is and how to call a service using JSON. I hope this article is useful for all students and beginners. If you have any suggestion related to this article then please contact me. 

Up Next
    Ebook Download
    View all
    Learn
    View all