Javascript - jQuery + ASP.NET – post-AJAX events

From jQuery, we get $(document).ready which is wonderful.
From ASP.NET, we get the UpdatePanel control which is fantastic.

 

One of the common problems that people have is regarding how to re-run the scripts after the UpdatePanel ajax update.

Here is one javascript-based solution – I consider these less intrusive than the code-behind solution with ClientScript.

Disclaimer – I learn this from previous projects I’ve worked on with personal experimentation – but I have not since read much documentation.

 

Original:

$(document).ready( function() {
$("a.link").css("border", "1px solid red");
})


The improved:

function setupLinkBorder( parentElement ) {
$("a.link", parentElement).css("border", "1px solid red");
}
$(document).ready( function() {
if (Sys &&
Sys.WebForms &&
Sys.WebForms.PageRequestManager &&
Sys.WebForms.PageRequestManager.getInstance()) {

Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function(src,args){
setupLinkBorder(args.get_panelsCreated()); // when UpdatePanel are first loaded
setupLinkBorder(args.get_panelsUpdated()); // when UpdatePanel are loaded via AJAX
});
}
})



  1. Split out the actual script into a separate function
  2. Make sure you have a Sys.WebForms.PageRequestManager.getInstance() object – the code for this part was a bit scary.
  3. Add event handler to handle pageloaded event fired by ASP.NET (which occurs for UpdatePanel update as well)
  4. Rely on the parent element property of jQuery to limit jQuery selector to elements within the updated panel only.  This ensures you don’t fire the jQuery code on elements that are outside of the UpdatePanel – which can be bad.