Raw AJAX In ASP.NET Using XMLHttpRequest And Generic Handlers
by Jeffrey Dale Starr, MCSD



Jeffrey Dale Starr, MCSD The advent of .NET 3.5 with ASP.NET AJAX has been a two-edged sword. On the positive side, it has become much easier to wire up AJAX functionality quickly. On the negative side, a lot of programmers are failing to learn the core mechanisms at work during an asynchronous event, and thus are not equipped to increase performance when needed through precise techniques.

AJAX within ASP.NET has become a black box. The ubiquitous UpdatePanel has become a cure-all: just stick whatever you need within the panel and update it, and Magic! - your changes appear without a postback.

Truth is, there is a rather large footprint that goes with the UpdatePanel. I did some performance testing last year to see exactly how much data was being transmitted to the WebServer when updating a simple TextBox within an UpdatePanel. Surprisingly, even though the text of my TextBox was something like "cat", I found that hundreds of characters were being sent over the network. That's because the UpdatePanel needs VIEWSTATE (among other things) to work its mojo. But in reality, if all I'm going to do is stick the word "cat" into my TextBox, and I'm going to pull that info from my DataServer, shouldn't I be able to limit my footprint to three characters?

The answer, thankfully, is 'Yes'. Fortunately, I was an early-adopter of AJAX. In fact, I was hired by one client solely to "AJAX-ify" their existing application, so it was all I did for 6 months. And back then, there was no such thing as an UpdatePanel, so everything I did was via raw AJAX (which even now is a valuable thing to know).

So let's walk through a simple example of how to wire up raw AJAX.

Step One: Set Up The JavaScript Functionality
Here's our scenario: we have a drop-down with a list of painting names. When the User selects a painting, we want to populate a label with the year that the painting was completed.



Here's what the HTML looks like. You'll notice the OnChange event that will fire off our asynchronous event:



Our OnChange event will do a combination of things that sets the AJAX operation in motion. When our page initially rendered, we created a JavaScript variable named "objAjax". We need for this object to be available throughout the life-cycle of the page, as you'll see.



Let's walk through each of these lines to explain what's going on.

Line 14: Instantiating the XMLHttpRequest object (further explanation below).
Line 15: Setting the "onreadystatechange" property. Basically, as the XMLHttpRequest object progresses through its steps, it updates this property with a value of 1-4. Every time that number changes, this event will fire.
Line 16: The URL that we will call. This is our Generic Handler. We are going to send the value of our drop-down as a parameter.
Lines 17 and 18: Configuring our header.
Line 19: Start the process.

On line 14, you'll see that we're initializing the XmlHttpRequest object. Since we want our function to work across browsers (including older ones), we're actually calling a function here that will return an XMLHttpRequest object based on our browser. Here is that function:





Step Two: Create The Generic Handler
Generic handlers have an extension of ASHX. They're equivalent to custom handlers written in C# or Visual Basic.NET in that they contain classes that fully implement IHttpHandler. They're convenient in the same way ASPX files are convenient. You simply surf to them and they're compiled automatically.

So we're going to add a new Generic Handler by clicking on the "Add New Item" link in VisualStudio:



Once we've created our Generic Handler, we need to grab the "id" parameter that we sent to it via the QueryString so that we can grab the proper record from our SQL Server database (if you have large amounts of data, it can be sent in the header as opposed to the QueryString, but that's another post for another day):



Now that we have the ID, we can query the database and return the proper Year Completed value to send back to our browser:



On line 38 you'll notice this is where we send our selected value back to the browser. For more complex functionality, I prefer to use JSON because of its lightweight, straightforward nature. In future blogs I'll explain how you can convert your JSON object to a JavaScript object and consume its properties.

Step Three: Wiring Up OnReadyStateChange
Now the value has been sent back to the browser so we need to grab it.



If you notice on line 24, we're checking the ReadyState of the XMLHttpRequest object. When it reaches "4", that means that our handler is finished doing its job and that it has returned a value to us.

On line 29 we grab the returned string, and on line 31 we update the label.



In Conclusion
This might seem like a lot of work...and compared to an UpdatePanel, it is. This situation isn't for everyone. For example, if your application will only have 10 concurrent Users EVER NO MATTER WHAT (which, I guess you could only guarantee if the client has 10 employees total), you should be fine. Or if you're dealing with a small page with a small VIEWSTATE. Or if you're dealing with a grid (I spent 2 solid months trying this kind of thing on a GridView. Trust me, it's not worth it).

But more importantly, I strongly believe that every developer should know how to do this from scratch, even if you never implement it. When we understand what's going on under the hood, we are much better equipped to run the machine.



Jeffrey Dale Starr is CEO and President of Purple Falcon Inc, a software development company located in San Francisco.
http://www.purplefalcon.com/