JQuery and WCF Working Hand-in-hand

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:

You don’t have to post the request to the code behind since the client will directly call the WCF service.

Page reload is avoided; hence it proves to be a performance optimized way.

User experience will be smooth, since there won’t be any post back occurrence.

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.

As a first step create a blank solution and name it as JQueryAndWcfSolution.

To the solution add a website with name DemoWebsite.

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 theBankingService.cs file and add a method called Deposit.

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.

Type: Type of method used to post the request. This could be GET, POST, PUT or DELETE.

Data: Parameter values that have to be passed to the WCF service method. The data has to be formatted as “{‘param1′:’value1’, ‘param2′:’value2’}”

ContentType: Type of the content that will be sent to the server.

DataType: Type of data that will be sent to the server.

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.

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.