Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Combining jQuery with ASP.NET AJAX

3.00/5 (2 votes)
14 Aug 2013CPOL1 min read 7.6K  
Combining jQuery with ASP.NET AJAX.

When we have existing ASP.NET AJAX UpdatePanels 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.

JavaScript
$(document).ready(function() {
   Function1();
   statement blocks....
   Function2();
}

becomes:

JavaScript
$(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.Ready functionality.

JavaScript
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

function EndRequestHandler(sender, args)  {
   if (args.get_Error() == undefined) {
        //repeat all functionality already defined within doc.ready
        DocReadyFunctionality();
  }
}

That's it.... enjoy both types of async functionality :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)