Published: 17 Sep 2007
By: Kazi Manzur Rashid
Download Sample Code

Sharing some of the Common Issues of ASP.NET Ajax Web Services.


In this article, I will answer some of the common questions which most of the developers face while working with ASP.NET Ajax Web Services.

Basic Call

The first thing I would like to cover is the complete signature of the Web Service method call. Certainly, there are many references available including the ASP.NET Ajax Documentation; but none of them highlighted it.

As you can see, you can pass any contextual data when calling a Web Method. This contextual data along with the method name is available in both Success and Failure callbacks. This extra data becomes handy when you use the same callback function for multiple web methods.

Consider the following example: I have a single callback function, which is used to update the different parts of the same page.

Certainly, you can use the set_defaultSucceededCallback and set_defaultFailedCallback instead of specifying the same callback repeatedly. Note that methodName is the Web Service method name. You can pass anything as the userContext parameter; but it will never be passed to the web method.

The next issue I would like to cover is handling the timeout of a Web Service method call. In the early days of ASP.NET Ajax, there was a separate callback function to handle the timeout. With the final release, a timeout is handled in the failedCallback, like so:

You can use the set_timout of your Web Service class to increase the default timeout value. If you want to increase all of your Web Services timeouts, then use Sys.Net.WebRequestManager.set_defaultTimeout(). This will also change the default timeout value of all your Ajax operations, including the UpdatePanel and manual invoking of Sys.Net.WebRequest.

Complex Data Type Interchange

In this section, I will show you how to implement some complex data types interchange with Web Services. Let's begin with arrays.

The above method is called as follows:

Now, let's see how to do the opposite: Pass an array to a web method.

We can pass the names array like so:

Next, we will see how to pass and return a Dictionary object. Some of you might argue that having a Dictionary object in the method signature always returns a serialization exception in regular Web Services. The ASP.NET Ajax framework allows a Dictionary object in the method signature. Consider the following example, which returns the weathers of different cities of Bangladesh:

We can call this method and format the result as follows:

Let's see how to pass a dictionary to a web method.

We can pass the weathers to the above web methods like the following:

Serializing a complete Object Graph

In this section we will see how to return/pass a custom class using Web Services. By default, the ASP.NET Ajax Framework only generates top-level classes in the Web Service proxy. Consider the following web method:

If you call this method like the following, you will get a JavaScript error saying that Address is undefined:

Since Address is a child object of the Customer class, the framework does not include it in the client proxy. To resolve this issue, add the GenerateScriptType attribute either in the web method or in the Web Service class:

Now you will be able to use the previously shown JavaScript code without any errors. The same holds true for enumerations. This issue has also been discussed by Dan Wahlin in this article.

Exclude Serialization

By default the ASP.NET Ajax Framework serializes all the public fields and properties of custom classes in the client proxy. Sometimes we want to exclude a few of the public fields/properties of those custom classes. To do that, use the ScriptIgnore attribute:

However, this will not have any effect if your web method response format is set to xml instead of default json. In the former case, use the XmlIgnore attribute like you do for regular Web Services.

Serialize incompatible types

The built-in JavaScriptSerializer class of the ASP.NET Ajax framework cannot serialize all the .NET types. Consider the following Employee class; if you try to return it from a web method, you will get a circular reference exception.

In situation like these, the JavaScriptConverter class comes into action. You can write your own custom converters, which transforms the incompatible types to compatible ones for the JavaScriptSerializer class. JavaScriptConverter is an abstract class which has the following signature:

Overriding the SupportedTypes property is mandatory. It instructs the ASP.NET Ajax Framework about the type the converter is responsible for, as in the following example:

If you are both accepting and returning the type, you will need to override both the getter and the setter. In our case we are only returning the Employee; thus we need to override the Serialize method and leave the others without any implementation, like so:

The Serialize method is simply streamlining the hierarchical employee in a dictionary object. To ensure the converter is called when the employee object is serialized you have to register it in the web.config file:

You can have anything for the name but the type attribute needs to be mapped to the type of the custom converter. Once you are done you can obtain the following output with few lines of JavaScript code.

Figure 1: Output obtained using a custom ASP.NET Ajax converter


Long Running Web Service Call

In this section I will show you how to display a progress indicator for a long running task, like the one shown in figure 2.

Figure 2: A progress indicator for a long running task


The design is very simple. First, we invoke a web method, which will start the lengthy task. It will create a status object that contains the progress information, which we will store in the ASP.NET cache. Next, we poll the task status by invoking another web method. Finally, we update the progress bar based upon the task progress. Let's take a peek at the Web Service code.

As you can see, we created the task ID based upon the user name to store it in the cache. Then we are doing some fake delay to simulate a real task and increasing the progress. Note that we cannot use the ASP.NET session, as the session access is always sequential. In the GetTaskStatus method we are simply returning the status from the cache. Now let's examine the client side code.

We are first doing some UI initialization and starting the lengthy task. Then we create a timer by calling setInterval, which polls the task status at two seconds interval. Once we get the status, we check whether the task is complete. If it isn't, we update the progress bar based upon its progress.

Soap Header

It is quite common to add AJAX support for our existing SOAP Web Service. Unfortunately the built-in WebServiceProxy class does not support either the SOAP header or any custom HTTP header. I've developed a custom proxy which has built-in support for both. Consider the following Web Service:

You will be able to call this method with the following code:

Now let see how to pass a custom HTTP header with the new proxy. Consider the following web method:

You will be calling the above method with the following code:

The main issue is that you have to manually write the proxy class for the Web Service. Also, the return type is always XML instead of a JSON object. The following code shows the web proxy for the above Web Service:

You can also use the above proxy for old versions of ASP.NET projects with ASP.NET Ajax Client Library.


All the above issues are based on feedback from the ASP.NET Ajax WebService Forum. If you experienced any issues that I have missed, please let me know and I will cover it in the future. 

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Kazi Manzur Rashid

Kazi Manzur Rashid, Nickname Amit is a Diehard fan of Microsoft Technology. He started programming with Visual Basic 5.0 back in 1996. Since then he has developed many diversified solutions in his professional career, which spans from Anti-Spyware Tool to Personalized Start Page. Currently He is wor...

This author has published 10 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category

Animating a Web Form using ASP.NET AJAX
In this article you will learn how to animate a webform using ajax.
Jquery Ajax
JQuery makes communicating with the server very, very easy. JQuery uses get(), getJSON(), and post(...
jQuery Deferred Objects Promise Callbacks
jQuery Deferred/Promise objects untangle spaghetti-like asynchronous code.
jQuery in Action 2nd edition: Queuing functions for execution
This article is taken from the book jQuery in Action, second edition. This segment shows how you can...
This is my custom article

You might also be interested in the following related blog posts

Using a Secure WebAPI Web Service from a Mobile App read more
Simple Demo WCF AJAX Web Service read more
Calling a RESTful Service like ASP.NET WebApi using WebApiClient read more
Code Builder for jQuery AJAX (Calling Web Services) read more
How to integrate RadControls for ASP.NET AJAX in a WebFarm or WebGarden scenario read more
LOB Gamification Service Admin Website: Data Services read more
ASP.NET Real-time Currency Converter using API (Google, Yahoo), Web service, and jQuery Ajax read more
ASP.Net Ajax AutoCompleteExtender Without Using Web Service read more
Calling Web Services Using AJAX read more
Using the West Wind Web Toolkit to set up AJAX and REST Services read more


Subject Author Date
placeholder Consuming WebService and WCF from jQuery. Eliza Sahoo 2/10/2010 6:38 AM
Great article on ASP.NET Ajax Web Services AMC Online. 9/18/2007 10:42 AM
placeholder Great article on ASP.NET Ajax Web Services AMC Online. 9/18/2007 10:42 AM
This article has been added into rss news Handy Chang 1/26/2008 4:59 AM
placeholder 1 issue Shashank k 3/20/2008 11:16 AM
RE: 1 issue Sonu Kapoor 3/20/2008 11:27 AM
placeholder Pretty good stuff !!! Braulio Diez botella 4/11/2008 6:44 AM
weighted stuff Arun Prasad 5/27/2008 2:46 AM
placeholder Where's the print link! John Spurlin 11/29/2008 7:54 AM
Great article - one of the scenarios I cannot get to work. Rik Beacroft 1/31/2009 8:20 PM
placeholder RE: Great article - one of the scenarios I cannot get to work. Sonu Kapoor 1/31/2009 10:39 PM

Please login to rate or to leave a comment.