May 7, 2012

Get the request complete event of ASP.NET Update Panel

Problem : 

This problem is related to the use of jquery with ASP.NET Update panel, I encountered it when i was trying to make a event scheduler using the update panel.

The problem was that when i load the new data in update panel, or when i fire an post-back asynchronously the event handlers of jquery attached to the previous dom inside the update panel gets lost. and i need to attach the events to newly updated dom elements.


Solution :

I begin my thought process and a ♫♪Tding♥♥♥  idea came into my mind, that when ever an ajax request is completed a request complete event is fired. Thus i need to capture this event and reinitialize my jquery code at the request completion. 


After reading a lot of documentations over Microsoft AJAX i discovered the code below.

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(  yourCallBackFunction );

And yes this line of code calls your function when ever any ajax request completes on the page. and of course this is the extension to Microsoft AJAX Framework.

Below is a complete demo of code.


  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
     function () {  

        $('#Calender li').each(function (index) {
            var Prev = $(this);
            $(this).find('p').click(function () {
                Prev.find('p').css('background-color', '');
                $(this).css('background-color', '#111');
            });
        })

    });

simply you can test as: (or i must say cup cake steps)

1. put a scriptmanager on the page
2. place an update panel on your page
3. put some buttons inside update panel
4. copy the following code and paste somewhere inside your page

<script type="text/javascript">


  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
     function () { 
                        alert('Request completed');
                  });

</script>

Thanks for reading hope this will help you some where..


1 comment: