When we have existing ASP.NET AJAX UpdatePanel
s in a page and then we want to attach events using jQuery, we face an issue relating to competing technologies placed together.
Whenever an UpdatePanel
does a partial postback of its contents, all controls are rendered afresh from the initial state and server side updates. As a result any control within
that container looses all events which were bound within the jQuery's $(document).ready()
handler. Hence all such functionality stops working.
Ideally we should not club two competing technologies together without checking out the contradictions. As different vendors provide their own updates, they often ignore
integration with their competition, wanting their users to use only their technology stack. As it turns out, this is not a wishlist item of any user.
However in this case, there's a backend hack that can be used to keep the ASP.NET AJAX doing its own stuff while allowing for new jQuery (or for that matter any JavaScript)
events to be attached.
AJAX library contains an event EndRequest
which can be handled with JS code. The piece of JS code is executed when an async postback has ended. If we execute our logic
contained in $(document).ready
again inside the EndRequest
handler, we can restore the functionality.
Step 1: Wrap all code present within document.ready
in another function so the hack is clean.
$(document).ready(function() {
Function1();
statement blocks....
Function2();
}
becomes:
$(document).ready(function() {
DocReadyFunctionality();
};
function DocReadyFunctionality(){
Function1();
statement blocks....
Function2();
}
Step 2: Take the EndRequest
event and within that bind the call to
DocReadyFunctionality
. This is in addition to existing Doc.Read
y functionality.
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_Error() == undefined) {
DocReadyFunctionality();
}
}
That's it.... enjoy both types of async functionality :)