JQuery and WCF Working Hand-in-hand

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

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
  {
      [OperationContract]
      [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.

  <system.serviceModel>
  		<behaviors>
  			<serviceBehaviors>
  				<behavior name="BankingServiceAspNetAjaxBehavior">
  					<serviceMetadata httpGetEnabled="true" />
  					<serviceDebug includeExceptionDetailInFaults="true" />
  				</behavior>
  			</serviceBehaviors>
  			<endpointBehaviors>
  				<behavior name="BankingServiceAspNetAjaxBehavior">
  					<webHttp/>
  				</behavior>
  			</endpointBehaviors>
  		</behaviors>
  		<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  		<services>
  			<service name="BankingService">
  				<endpoint address="" behaviorConfiguration="BankingServiceAspNetAjaxBehavior"
  				 binding="webHttpBinding" contract="BankingService" />
  			</service>
  		</services>
  </system.serviceModel>

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.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read