Partial page updates with 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.

I have already touched briefly on the enormous benefits of AJAX via the jQuery library in my previous post, so here is a concrete example showing how to inject HTML directly into your ASP.NET page without using a ScriptManager or the Microsoft JavaScript library. Unlike a lot of code examples, I prefer to keep mine simple otherwise the point you are trying to get across is lost amongst unrelated logic (one memorable case showed the movement of the planets in relation to one another, which was fascinating but of absolutely no relevance!). So in the interests of clarity, I’ve kept this basic but the potential for what you can achieve and the gains in efficiency and performance speak for themselves. I’m using a page method rather than calling a service because it’s simpler, but a direct service call would work just as well.

The ASP.NET markup consists of an HTML button and a single div called updateRegion which is where we will inject the result from our page method. As you can see, you don’t need a lot of markup in the page to achieve great results and with the exception of the form itself, there is not another server control in sight. This is the transition from the classic ASP.NET model of entire pages being generated by the server, to specific regions of the page being supplied on-demand by the server and then processed client-side. As a result of this design shift, pages will contain fewer and fewer server controls in the future.

Web form markup:

Note: make sure you terminate your div with a proper closing tag rather than the shorthand ‘/>‘ version. When I first did a partial update using a div without a closing tag I ran into all sorts of HTML display issues and it took me a while to work out what was causing it. By changing the div’s inner HTML, I ended up with an unterminated div which became the parent of all the sibling elements after it.  So if in doubt, let Visual Studio generate the closing tag for you by just typing ‘>‘. It will select the appropriate one for that element based on whether it can contain child elements or not.

The page’s JavaScript provides the button click handler (which makes the jQuery ajax call to a page method) and the asynchronous callback functions for error and success. Notice I said error first, which was intentional. Always consider and deal with error situations first rather than leaving them as an afterthought – which will almost certainly be forgotten about!

Finally, the render function injects the HTML returned by the server into the div container on the page. The hardcoded JSON parameter is there to show how it’s done, but obviously you would dynamically generate this at run-time based on user-input or interaction with the page. There’s no limit to how many parameters you can pass via JSON but if there are no parameters, remember to still pass in an empty JSON string surrounded by opening and closing curly braces ('{}') otherwise it may cause the AJAX call to fail.

Client script:

As you can see, there really isn’t a lot of script required to add asynchronous calls to your web pages. Also notice how the XmlHttpRequest object returned by the jQuery ajax function is stored so that incomplete requests can be cancelled before a new one is started. This doesn’t cancel the request on the server (that requires a bit more effort, which I’ll cover in a separate post) but it will stop multiple asynchronous responses from being received by the client – and potentially not in the order they were submitted, which is an inherent problem with AJAX requests.

For this example, I created a very simple model interface and class to store data which will be displayed on the web page:

I’ve been a bit more creative with the code-behind page method to show the sort of dynamically generated HTML which can be sent back to the client although the data could be in any format (plain text, JSON, HTML, XML, MXML – it’s up to you).

Code-behind (server):

This outputs a very basic table but you can generate complex data grids, calculation results, embedded objects such as Flash (SWF) movie files, image tags, RSS – the sky really is the limit. And never be tempted to include inline styling in the markup. Use class names for existing CSS which is linked to the page (and therefore already cached at the browser). This makes the amount of data you send back to the client much smaller, resulting in faster response times. AJAX is always about being fast and lightweight.

Here is the end result. OK, it won’t win any design awards but it was achieved without a postback and according to Firebug, only 20 bytes were sent to the server in the message body.

Before                                            After


Obviously the server response will vary depending on how much data you are returning so this isn’t an issue, but the request size is a fraction of what a full or partial-postback would be. In fact you would struggle to create a Web Form with just one server control on it which posts so little data back to the server because the form’s entire ViewState is included in every postback.

And just to reinforce the point, here are the actual response times and amount of data sent according to the Firebug net window. The first two requests are when the ASPX page and jQuery library are first loaded in the browser, and the third request is the AJAX call to the GetUserDetails page method when the button is clicked. The ASPX page size was 1.6KB and took 62ms (remember this is for a Web Form containing a single non-server HTML button). Whereas the GetUserDetails page method returned far more visible HTML content but took less than 1/4 of the time at just 15ms. The reason the initial page load is so much slower is because of the overhead incurred by the ASP.NET model of compiling server pages via the ASP.NET runtime when a request is first received (but even pre-compiled pages can’t compete on performance).

I have seen production pages containing so many complex server controls that the postback size and response times were appalling. No self-respecting web developer should think this is acceptable, and when you reach that point, you really need to start questioning your design strategy and start utilising AJAX properly rather than relying on server controls which make expensive postbacks or partial-postbacks.

And lastly, in case you were wondering where the table styling comes from, it was achieved with a small amount of CSS in the page head section. This is the beauty of CSS – you only have to declare it once and it will affect all of your page elements which have a matching element type/id/class. The combination of dynamic HTML and CSS can create a very compelling user experience.


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, CSS, 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