Thursday, October 28, 2010

ASP.NET UpdatePanel, jQuery and Async postback

It's common to have jQuery plug-in (or any other JS plug-in) to attach it's behavior to some DOM objects upon document load. It's usual for many plug-ins to subscribe to events of the elements of interest. A simple example, attach multiply row values behavior via JS plug-in to ASP.NET GridView control (which is rendered as a <table> element):

After page is loaded a new behavior is available to the grid veiw (in this case the plug-in simply recalculates values for row cells upon user input).

The problem may arise when the GridView control is inside an UpdatePanel and an sync postback occurs. In this case the old table is deleted and new markup is rendered in it's place. This means that old DOM elements are deleted and no active event subscriptions exist anymore. After postback plug-in behavior is not active and should be reattached once again. To this MS Ajax client library can be used to handle async postback event when reposnse is received and rendered:

Note: if the init script creates any DOM elements outside the update panel then duplicate elements can be created after async postbacks. This should be handled separately.