For those looking to get up and running with ASP.Net AJAX, using the following design patterns can do wonders for keeping your code clean and organized, while also helping keep your sanity when working with complex pages.

The first point to address is how we actually fire off partial page postbacks.  ASP.Net will do this automatically when using server controls within an updatepanel, or by using triggers, but these built-in features leave a lot to be desired.  For example, what if I want to fire off a postback from something other than an ASP.Net server control?

AJAX __doPostBack

In the example above, I’d like to do a postback when clicking on either of the divs within my update panel.  By calling the __doPostBack function directly, I’m able to fire off a postback as well as specify both the EventTarget and EventArgument variables.  This offers a HUGE amount of flexiblilty as we’ll see later.   Also Notice the hidden input fields, and how they have the same name as parameter 1 of the __doPostBack command.  This has the same effect as adding an UpdatePanel Trigger, and tells ASP.Net that when cmdSaveRecord is fired, the UpdatePanel upDemo should be reloaded.  If you leave this out, the entire page will be reloaded.  Note that you can place the hidden field in any UpdatePanel that you like, and only that updatepanel will be refreshed, regardless of where you execute __doPostBack from.

Now let’s look at the server side where we’ll be processing these Ajax Postbacks.

AJAX ProcessAjaxPostback

I use the code structure above for every page that does any type of postback, whether it’s Ajax enabled from an UpdatePanel or a full page postback.  This allows all postback handling code to be centralized in the ProcessAjaxPostBack method.  Notice that the first task of this method is to grab the EventTarget and EventArgument parameters.  These are the two parameters I passed in to the __doPostBack method from the client side.  Following this is an if/elseif loop which examines the first parameter and executes the appropriate code.  On complex pages, this function will get rather large, so It’s a good idea to build individual functions to do the work for each postback.  See the calls to SaveRecord and DeleteRecord above.

I use the code above in all of my web applications and have not run into any roadblocks or limitations.  I find it keeps my source code clean and understandable, on simple and complex pages.  I hope you enjoyed this article and I look forward to hearing your feedback!

Kick It on