Wednesday, May 20, 2009

JavaScript with update panel

Today I ran into a problem. I have a search web page that renders categorized search results within an UpdatePanel. Then I have a separate web control that has some Jquery script to hide and show the different categories. The control renders only the categories that have been chosen by the user. When a search is done both the search results and the category filter control are rendered asynchronous. To decouple the rendered links and elements from the JavaScript the script has a

$(document).ready(function()




that kicks of the script and puts the needed attributes in place.

The problem is that the $(document).ready function only kicks in when the page is posted or reloaded, and not when an async. postback is done by the UpdatePanel.


Then Joel had the answer,  in the first function the code that has to run on every post needs to be wrapped wit a function that is called by the scripts generated by ASP.NET AJAX framework



Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded


. the code looks like this.



$(document).ready(function() {
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
function pageLoadedHandler() {

Code to run on async postback...

}
});