Asynchronous WCF from client perspective, invoked by JQuery — an example.

In my earlier example, “invoking-multiple-wcf-service-asynchronously-and-in-parallel-from-an-aspx-page” the WCF service itself was asynchronous and by calling multiple services in the same request, I was able to get more than one task done in parallel. Everything happened in the same single request, the WCF service was invoked after the request hits the server, & the response made it to client only after, all the async services were done successfully OR page timed out. The VS2010 template I used for my earlier example was “WCF Service”.

The following example is little different.This also calls a WCF service asynchronously but from JQuery. I used the VS2010 template “AJAX-enabled WCF Service”, since Javascript/JQuery would invoke this service and not in codebehind. I just want to highlight the difference between the two VS2010 templates – namely ‘WCF service’ & ‘AJAX-enabled WCF service’ — and when to use what. In the following example, the WCF service is invoked asynchronously through JQuery ajax every 10 sec. It fetches some categories from the Northwind Db and keeps appending to the Dropdownlist. In the meantime, the rest of the page is also active. In this example, say I can edit the Person’s Firstname, LastName or email, in a pop-up dialog box. I used the javascript timer to invoke the AJAX-enabled WCF service every 10 sec.Here’s the complete code-sample along with a screen shot of the page in action.


<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="jQueryWCF2.aspx.cs" Inherits="jQueryWCF2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<script src="" type="text/javascript"></script>
<script src="" type="text/javascript"></script>
<script src="" type="text/javascript"></script>
<script src="" type="text/javascript"></script>

<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.7.2.custom.min.js"type="text/javascript"></script>
<link href="Styles/ui-lightness/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
var result = "";
window.setInterval(GetServiceData, 10000);
function GetServiceData() {
type: "POST",
contentType: "application/json",
dataType: "json",
data: "{}",
url: "Services/NorthWindAJAXEnabledWCFService.svc/GetCategories",
success: function (data) {
    result = data.d;
    for (var i = 0; i < result.length; i++) {
        $("<option />")
    $('#p1').html('<br><b>Refreshed at:-  ' + new Date() + '&nbsp;&nbsp; Total Categories Fetched=' + $('#categories option').size() + '</b>');

error: function (XMLHttpRequest, textStatus, errorThrown) {
beforeSend: startingAjax,
complete: ajaxCompleted,
cache: false,
async: true
function startingAjax() {

function ajaxCompleted() {

$(document).ready(function () {
        autoOpen: false,
        draggable: true,
        title: "Edit Person Details",
        open: function (type, data) {
    $('#btnEdit').click(function () {
    $('#btnSave').click(function () {
        $('#Fname').html($("[id$=TextBox1]").val() + '');
        $('#Lname').html($("[id$=TextBox2]").val() + '');
        $('#email').html($("[id$=TextBox3]").val() + '');

    <b>Available Categories:&nbsp;</b><select id="categories"></select>
    <br />
    <div id="p1" style="color:Green;"></div>
    <hr />

    <div id="Others">
    <tr ><td>FirstName:&nbsp;</td><td><div  id="Fname">John</div></td></tr>
    <tr ><td>LastName:&nbsp;</td><td><div  id="Lname">Doe</div></td></tr>
    <tr ><td>Email:&nbsp;</td><td><div id="email"></div></td></tr>
    <tr><td><input type="button" id="btnEdit" value="Edit"   /></td></tr>

    <div id="OthersEdit">
    <li>FirstName:&nbsp;&nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></li>
    <li>LastName:&nbsp;&nbsp;<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></li>
    <li>Email:&nbsp;&nbsp;<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></li>
    <input type="button" id="btnSave" value="Save"   />


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class NorthWindAJAXEnabledWCFService
    private string _DBConnection1 = ConfigurationManager.AppSettings["conStr3"];
    // 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";
    public void DoWork()
        // Add your operation implementation here

    // Add more operations here and mark them with [OperationContract]
    // Add more operations here and mark them with [OperationContract]
    public CategoryDTO[] GetCategories()
        List<CategoryDTO> values = new List<CategoryDTO>();
        SqlConnection cnn = new SqlConnection(_DBConnection1);
        SqlDataAdapter cmd1 = new SqlDataAdapter("select CategoryID,CategoryName,Description from Categories WHERE CategoryID is NOT NULL order by CategoryID", cnn);

        DataSet ds = new DataSet();
        cmd1.Fill(ds, "Categories");
        DataTable dt = ds.Tables[0];
        foreach (DataRow dr in dt.Rows)
            CategoryDTO _dto = new CategoryDTO();
            _dto.CategoryID = int.Parse(dr["CategoryID"].ToString());
            _dto.CategoryName = dr["CategoryName"].ToString();
            _dto.Description = dr["Description"].ToString();
        return values.ToArray();


Thanks for reading.

This entry was posted in WCF. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s