JQuery and WCF Working Hand-in-hand

by V.N.S Arun

Learn how communication between JQuery and WCF works and why this combo is so special, as we create a sample application.


In this article we will learn how to call a WCF service from JQuery. We will also be creating a sample web application for the demonstration purposes and we'll explain the code as we go along.

The JQuery library can be downloaded from here. The version of JQuery that we are going to use is 1.4.2.min.

What's the Advantage of Calling WCF From JQuery?

For readers who are not aware of JQuery here is a little lead in. JQuery is a JavaScript library which helps in traversing through the HTML elements on the webpage easier. For example you can access a TextBox with id txtName as $('#txtName'). Providing the effects and animations for the controls are also relatively simple when compared with the implementation using raw JavaScript.

Apart from the UI level operations it is also possible to call the WCF or WebServices using JQuery. Below are the advantages of calling WCF service from JQuery:

  1. You don't have to post the request to the code behind since the client will directly call the WCF service.
  2. Page reload is avoided; hence it proves to be a performance optimized way.
  3. User experience will be smooth, since there won't be any post back occurrence.
  4. Calling WCF using JQuery also gives the provision to perform callbacks for both success and error scenarios.

Creating a Sample Application

Let us create a sample application.

  1. As a first step create a blank solution and name it as JQueryAndWcfSolution.
  2. To the solution add a website with name DemoWebsite.
  3. Create a folder under the website named Script. Add the JQuery library to it.

Creating the WCF Service

Add AJAX Enabled WCF service to WebSite naming BankingService.svc. Go to the BankingService.cs file and add a method called Deposit.

Below is the code:

  [ServiceContract(Namespace = "")]
  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class BankingService
      [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]    
      public string Deposit(string accountId, string firstName, string lastName, string amount)
          return string.Format("Mr. {0} {1}, Sum of {2} USD has been deposited to your account {3}", firstName, lastName, amount, accountId);

Note that the Deposit method is decorated with the attribute WebInvoke. This attribute is required in order to invoke this method from JQuery.

WebInvoke attribute is supplied with three properties.

  1. Method: WCF service can be called from JQuery through GET, POST, PUT or DELETE method. The method value provided in the attribute should be the same with the one provided in the JQuery code.
  2. BodyStyle: This allows the developer to mention whether the request should be wrapped, response should be wrapped, both should be wrapped or nothing should be wrapped.
  3. ResponseFormat: Supported response formats are JSON and XML.

In our demo application we will use GET method, NoWrapping (WebMessageBodyStyle.Bare) and response format as JSON.

WCF Configuration Entries in Web.Config

A crucial part while creating a WCF service is configuring the System.ServiceModel tag in the web.config file. Below is the configuration entry for our WCF BankingService.

  				<behavior name="BankingServiceAspNetAjaxBehavior">
  					<serviceMetadata httpGetEnabled="true" />
  					<serviceDebug includeExceptionDetailInFaults="true" />
  				<behavior name="BankingServiceAspNetAjaxBehavior">
  		<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  			<service name="BankingService">
  				<endpoint address="" behaviorConfiguration="BankingServiceAspNetAjaxBehavior"
  				 binding="webHttpBinding" contract="BankingService" />

In the above configuration note that the binding used is webHttpBinding. It is also important to set the httpGetEnabled and includeExceptionDetailInFaults attributes in the behaviour to true.

Webpage and JQuery Code

Let us create the webpage and name it BankDeposit.aspx. Below is the HTML:

      <form id="frmBanker" runat="server">
          <table style="width: 506px">
                  <td class="style2">
                      Account Number:
                      <input id="txtAccountId" type="text" />
                  <td class="style2">
                      First Name:
                      <input id="txtFirstName" type="text" />
                  <td class="style2">
                      Last Name:
                      <input id="txtLastName" type="text" />
                  <td class="style2">
                      <input id="txtAmount" type="text" />
                  <td class="style2">
                      <input id="btnDeposit" type="button" value="Deposit" />

Below is the JQuery code on the webpage:

       <script src="Script/jquery-1.4.2.min.js" type="text/javascript"></script>
       <script type="text/javascript">
           $(document).ready(function() {
               $('#btnDeposit').click(function(event) {
                   var parameters = '{"accountId:"' + $('#txtAccountId').val() + '","firstName":"' + $('#txtFirstName').val() + '","lastName":"'
                               + $('#txtLastName').val() + '","amount":"' + $('#txtAmount').val() + '"}';
                       type: "GET",
                       url: "http://localhost/DemoWebsite/WCF%20Service/BankingService.svc/Deposit",
                       data: parameters,
                       contentType: "application/json; charset=utf-8",
                       dataType: "json",
                       processdata: true,
                       success: function(result) {
                       error: function(error) {
                           alert("Error occured while calling the Banking Service!");

The above JQuery function will be invoked when the button btnDeposit is clicked. You will notice a number of properties being set in the JQuery click event handler code. Lets look at this step by step.

  1. Type: Type of method used to post the request. This could be GET, POST, PUT or DELETE.
  2. Url: The URL of the WCF Service. You could also provide the relative path if the service lies under the same website. The name of the method to be invoked should be appended to the URL as http://localhost/DemoWebsite/WCF%20Service/BankingService.svc/Deposit.
  3. Data: Parameter values that have to be passed to the WCF service method. The data has to be formatted as "{'param1':'value1', 'param2':'value2'}"
  4. ContentType: Type of the content that will be sent to the server.
  5. DataType: Type of data that will be sent to the server.
  6. Success: This function will get executed if the service call and execution of the service method is successful. The return value of the service method will be passed to the success callback function.
  7. Error: This function will get executed if the service call fails or any exception is thrown. The error details will be passed to the error callback function.


I hope this article gives you a better understanding of calling WCF services from JQuery, while establishing the supremacy of the combination. If you have any queries please make use of the comments section.

Happy reading!

Related Articles

This article was originally published on Monday Nov 22nd 2010
Mobile Site | Full Site