Thursday, March 14, 2013

Running a Client-Side Javascript Method with an AJAX UpdatePanel

Have you ever needed to run a client-side javascript method when an AJAX UpdatePanel makes an asynchronous postback?  I needed to do that recently.  I was creating a ASP.Net control for a customer that  provided a cool chat feature to their customer support.

When the control performed an async post back, I need a client-side method to be fired as soon as it executed successfully.  Microsoft provides a pretty easy way to do it, but you need to know the trick.  Here it is:

1:  <script type="text/javascript">  
2:      function MethodToFire()  
3:      {  
4:        /* Do something on client side */  
5:      }  
6:       /* Sys function to enable cient side requests */  
7:      Sys.Application.add_init(appl_init);  
8:       /* The actual function to initialize it. Note the "add_endRequest" */  
9:      function appl_init() {  
10:        var pgRegMgr = Sys.WebForms.PageRequestManager.getInstance();  
11:        pgRegMgr.add_endRequest(MethodToFire);  
12:      }  
13:  </script>  
14:  <asp:UpdatePanel Id="UpdatePanel1" runat="server">  
15:        <Triggers>  
16:          <asp:AsyncPostBackTrigger ControlId="Timer1" />  
17:        </Triggers>  
18:       <ContentTemplate>  
19:            <!-- Some content in here! -->  
20:       </ContentTemplate>  
21:  </asp:UpdatePanel>   

With this, the "MethodToFire" function (line 11) will fire after the Async method returns. Want to fire it before the Async method executes? Use the pgRegMgr.add_beginRequest method instead.

Happy developing!

No comments:

Post a Comment