Using JQuery to call a WCF Service in an ASP.Net application

In this post I would like to show you with a hands-on example how to invoke a WCF service from JQuery. I have already posted a few posts regarding JQuery and server communication.Have a look in this post and in this post. This is a similar post .

In order to follow what I am about to say in this post, I assume that you know what JQuery is and have a basic understanding of how to traverse the DOM or handle events with JQuery.

You can find more posts regarding JQuery by clicking here. So we can invoke an AJax enabled WCF service from JQuery as long the binding is webHttpBinding.

 

1) Launch Visual Studio 2010 (express edition will also work) and create a new empty website.Choose a suitable name for your website.Choose C# as the development language.

Add a new item in your project , a web form. Name it jQueryWCF.aspx.We are going to have some <a> links in the page. We are going to instantiate some calls to the WCF service through JQuery.

These links represent the names of Liverpool footballers. This is the code for the markup

<body>
  
        <p>Liverpool Players</p>
 
            <a href="#">Steven</a> 
            <a href="#">Kenny</a> 
            <a href="#">Robbie</a>    
  
    <br />
 
    <br />
 
    <br />
    <div id="loginfo">
    
    </div>
    <br />    
    <div id="res">
    
    </div>
</body>

 

Nothing difficult in this code.

2) Add another item to your website, an Ajax-enabled WCF service.Name it FootballersInfo.svc. The markup is generated automatically

<%@ ServiceHost Language="C#" Debug="true" Service="FootballersInfo" 
CodeBehind="~/App_Code/FootballersInfo.cs" %>

3) In the App_Code folder we need to add a new item, a class file. I name it Footballers.cs

This is the code for the class

[DataContract]
public class Footballers
{
    [DataMember]
    public string FirstName { getset; }
 
    [DataMember]
    public string LastName { getset; }
 
    [DataMember]
    public DateTime BirthDate { getset; }
 
}

This is a simple class with 3 properties.

Also in the App_Code special folder we have the FootballersInfo.cs

The code for this class follows. Have a look at the comments. I would use those lines if I would use a HTTP GET.In this example I will use HTTP POST.

In this class we have a method (GetFootballerInfo) that gets a string as an input parameter and we return back to the calling code a footballer object depending on the input string parameter (name)

public class FootballersInfo
{
// To use HTTP GET, add [WebGet] attribute. 
//(Default ResponseFormat is WebMessageFormat.Json)
	// To create an operation that returns XML,
//     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
//     and include the following line in the operation body:
//   WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
 // Add more operations here and mark them with [OperationContract]
 
    [OperationContract]
    public Footballers GetFootballerInfo(string name)
    {
        Footballers footballer = null;
 
        if (name == "Steven")
        {
            footballer = new Footballers
            {
                FirstName = "Steven",
                LastName = "Gerrard",
                BirthDate = new DateTime(1980, 11, 11),
 
            };
        }
 
        if (name == "Kenny")
        {
            footballer = new Footballers
            {
                FirstName = "Kenny",
                LastName = "Dalglish",
                BirthDate = new DateTime(1950, 11, 11),
 
            };
        }
 
        if (name == "Robbie")
        {
            footballer = new Footballers
            {
                FirstName = "Robbie",
                LastName = "Fowler",
                BirthDate = new DateTime(1975, 11, 11),
 
            };
        }
 
   
 
        return footballer;
    }
} 

 

4) Now we need to write some JavaScript code that will invoke the WCF service and get back the results from the service and display them on the screen.Add a folder to your website, called scripts.

Add a new item to the scripts folder, a javascript file. Name it jQueryWCF.aspx.js . Go to the main JQuery website -http://jquery.com/- and download the latest Jquery library. Include those library files in the scripts folder.

In the head section of the jQueryWCF.aspx page add the following

<head runat="server">
    <title></title>
   
 
  <script src="scripts/jquery-1.7.js" type="text/javascript"></script>

    <script src="scripts/jQueryWCF.aspx.js" type="text/javascript"></script>
</head>

 

I will post below the contents of the jQueryWCF.aspx.js  and I will explain what I do

 
$(function() {
    $("a").click(GetFootballerInfo)
 
 
 $("#loginfo").ajaxComplete(function(event, xhr, options) { 
$(this).append("complete <br/>"); })
   .ajaxError(function(event, xhr, options) { $(this).append("error <br/>"); })
   .ajaxSend(function(event, xhr, options) { $(this).append("send <br/>"); })
   .ajaxStart(function(event, xhr, options) { $(this).append("start <br/>"); })
   .ajaxStop(function(event, xhr, options) { $(this).append("stop <br/>"); })
   .ajaxSuccess(function(event, xhr, options) { $(this).append("success <br/>"); });
});
 
 
 
function GetFootballerInfo(event) {
    var footballerName = $(this).text();
    $.ajax(
        {
            type: "POST",                                           
            url: "FootballersInfo.svc/GetFootballerInfo",     
            data: '{ "name": "' + footballerName + '" }',           
            timeout: 7000,                                          
            contentType: "application/json",                       
            dataFilter: parseJson,
            success: onSuccess                
        });
}
 
function parseJson(data, type) {
    var dateRegEx = new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)
(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)\\\\/\\"''g');
    var exp = data.replace(dateRegEx, "$1new Date($2)");
    var result = eval('(' + exp + ')');
    return result.d;
}
 
function onSuccess(footballer) {
 
    var html = "<ul>";
 
    html += "</ul>";
   html += "<br/>First Name: " + footballer.FirstName;
  html += "<br/>Last Name: " + footballer.LastName;
  html += "<br/>Birthdate: " + footballer.BirthDate;
  
  $("#res").html(html);
}

 

When the link is clicked then I call the GetFootballerInfo function. The function does the following:

1) I get the text of the link that was pressed, (footballer name). Then I make a low level call to the ajax JQuery method to perform the asynchronous HTTP (Ajax) request and fill in all the parameters the method requires.Then I use HTTP post to pass the data to the WCF service (type: "POST",  )

2) The URL or endpoint is set to the  (url: "FootballersInfo.svc/GetFootballerInfo",). We invoke the GetFootballerInfo method.

3) Then I define that the input parameter is in JSon format (data: '{ "name": "' + footballerName + '" }',).What I mean is that we serialise the input data as JSon format. WCF will make a note of that and deserialise it.

4)  We have a timeout of 7 seconds  (timeout: 7000, )

5)  We tell WCF that JSon format is what we are going to pass it and we expect JSon format as a response. ( contentType: "application/json",  )

6) The WCF will return JSon to the asynchronous call and JQuery will attempt to parse that JSon. But that does not work well with datetime fields.We can get round that by writing our own parsing JSon datetime method. (  dataFilter: parseJson, ). Have a look at the parseJson method.

7) When everything is successfull we call the onSuccess method. (success: onSuccess). Have a look at the onSuccess method. We get back the answer from the server and then using simple JQuery we stick that output to the page  ($("#res").html(html); })

Finally I would like to say a few things about the global Ajax events. This is the only bit of code I have not explained.

 

 $("#loginfo").ajaxComplete(function(event, xhr, options)
 { $(this).append("complete <br/>"); })
    .ajaxError(function(event, xhr, options) { $(this).append("error <br/>"); })
    .ajaxSend(function(event, xhr, options) { $(this).append("send <br/>"); })
    .ajaxStart(function(event, xhr, options) { $(this).append("start <br/>"); })
    .ajaxStop(function(event, xhr, options) { $(this).append("stop <br/>"); })
    .ajaxSuccess(function(event, xhr, options) { $(this).append("success <br/>"); });

What I do here is basically using these events to get information such as when the ajax call  started, was sent, was successful,completed and finally stopped.I also find out if something was wrong (error). I print this information to the screen.By all means have a look in the documentation for global Ajax events.

By all means use Firebug to debug / place breakpoints for the .js files.

5) Finally view the page in the browser and click the link. The asynchronous call to the service will be made. The WCF service will get the parameter and will return back JSon results that JQuery will know how to parse.

Have a look at the picture below to see what happened when I loaded the page and clicked one of the links.

 

Now I would like to show you how to use Firebug which is an excellent add-on to do some basic debugging.You must download firebug and invoke it.I will add a watch (footballerName) and place a breakpoint.Then I  run the page again. Have a look at the picture below

 

Finally we can see the JSon response the WCF Service sent back to the calling application. Have a look at the picture below.

 

So we saw how easy it is to invoke a WCF Service with JQuery. Hope the screenshots helped to clear things out.

Email me if you need the source code.

Hope it helps !!!

3 Comments

Comments have been disabled for this content.