Page Method via jQuery AJAX

UPDATE: I have left this article here for historical reasons but you should now consider ASP.NET Web Forms as obsolete due to it not supporting unit-testing and the amount of data that is passed between client and server. I recommend a modern web technology such as MVC 4 (or later) combined with javascript libraries such as jQuery and Knockout.

Adding a web service reference to a ScriptManager control on a web form generates proxy JavaScript code in your page which makes it very easy to call service methods asynchronously (which is more efficient than postbacks or partial-postbacks).

A similar result can be achieved with even less effort by using the jQuery ajax function to call a page method declared in the code-behind file. A page method is a public static method with the [WebMethod] attribute so you must import the System.Web.Services namespace. However, remember that this is a static method on a web form class where thread concurrency is expected, so do not be tempted to read or write to shared data via static fields. Although appropriate locking will solve data synchronisation issues, blocking HTTP request threads will have a major impact on performance so it is strongly recommended that you keep your code-behind class stateless. To ensure thread-safety and scalability, only use local objects created within the page method and if you need to persist data across separate requests, use the HttpContent.Current.Cache property. One last point is that cross-page calls to other page methods are not permitted for ASP.NET security reasons.

Code-behind (server):

This is a very simplistic example, but a page method is an ideal place to make calls to a service to obtain the data which will be sent back to the client. This may be in the form of plain text, JSON, XML, or simply HTML markup which you can inject into the page.

Calling the page method from the client is quite straight forward thanks to jQuery’s ajax function which takes the URL to the page method, and optionally some JSON parameters.

Client script:

Note the resulting value obtained in the getDataSuccess function is via the <param>.d property which is new to ASP.NET 3.5. Earlier versions can use the parameter value directly. Also note the jQuery ajax function returns an XmlHttpRequest object (which is what makes AJAX calls possible in the first place).

The reason I call XmlHttpRequest.abort first is to prevent overlapping AJAX requests. When you enter the world of asynchronous requests, you will quickly learn the problems associated with receiving responses at undefined times. For example: say you have two buttons on your page (button A and button B). Both buttons trigger AJAX calls to a page method and a single div displays the response from either button. The user clicks button A and then clicks button B immediately afterwards, so they would expect to see the result from button B. However the response from button A is a fraction slower and overwrites the result for button B. You see the problem? It’s all about synchronising the responses from your AJAX calls, and how you do this may depend on the particular functionality you’re trying to create. But by far the simplest solution is just to cancel the previous AJAX call, which is what XmlHttpRequest.abort does. This won’t cancel pending requests on the server, but it will stop their responses firing the events which trigger your JavaScript event handlers. And it will therefore guarantee that responses are displayed in the same order that requests are made in. Don’t worry too much if you don’t have experience of asynchronous (parallel) operations, as long as you are aware of the potential problems and the unexpected results you can sometimes face.

Here is some web form markup with a button which initiates the AJAX call:

The reason I’ve added the ‘Async’ suffix to the onclick event handler name is because that’s exactly what it is – asynchronous. The getDataAsync function starts an AJAX request and then returns control to the caller immediately (it does not block until the response is received) meaning that the user can continue working in the browser while the AJAX request is being made in the background. It’s always a good idea to make it clear in your code which functions/methods are asynchronous because of the added complexity they bring with them.

In summary, the jQuery ajax function doesn’t do anything radically new except that you don’t need a ScriptManager control on your page for it to work. It still uses the XmlHttpRequest object, and just like ScriptManager it generates all of the necessary proxy JavaScript for you to make asynchronous server calls.  And it is more lightweight than doing partial-postbacks because you are literally passing only the data you need and nothing more, rather than posting the web form and portions of its view state back to the server each time.


About Phil Munro

I have been developing commercial desktop and distributed web applications with Microsoft technologies since 1997.
This entry was posted in AJAX, ASP.NET Web Forms, Javascript, jQuery. 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