JQuery and WCF Working Hand-in-hand

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.



JQuery and WCF Working Hand-in-hand

Webpage and JQuery Code

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

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

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) {
                   event.preventDefault();
                   var parameters = '{"accountId:"' + $('#txtAccountId').val() + '","firstName":"' + $('#txtFirstName').val() + '","lastName":"'
                               + $('#txtLastName').val() + '","amount":"' + $('#txtAmount').val() + '"}';
                   $.ajax({
                       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) {
                           alert(result);
                       },
                       error: function(error) {
                           alert("Error occured while calling the Banking Service!");
                       }
                   });
               });
           });
       </script>
 

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.

Conclusion

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





About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds