Wednesday, April 29, 2015

ASP.Net Intercept postback event

Ever needed to intercept the ASP.Net postback event from the client-side using javascript so you can override or customize something? Here's a simple way to do it.

Code:
   ...  
   
   <!-- intercept postback event -->  
   <script language="javascript" type="text/javascript">  
     // get reference to original postback method before we override it  
     var __doPostBackOriginal = __doPostBack;  
   
     // override  
     __doPostBack = function (eventTarget, eventArgument) {  
       // show progress modal  
       ShowProgress();  
   
       // postback  
       __doPostBackOriginal.call(this, eventTarget, eventArgument);  
     }  
   </script>  
 </body>  
 </html>  

First you need to get a reference to the original __doPostBack event and save it in the __doPostBackOriginal variable. This is necessary so you can trigger it later.

Once you have the reference to the original postback event you can override __doPostBack. This is where you'll want to put your custom code. In this example, I call a ShowProgress() method. This is where I trigger a custom bootstrap modal so for any postback you see a progress spinner.

After you've added your custom override you call __doPostBackOriginal.call(this, eventTarget, eventArgument); to trigger the original postback event.

It's worth noting that the __doPostBack javascript event is only rendered when it is needed. It will be rendered by ASP.Net whenever you add a web server control to your form, with the exception of Button and ImageButton controls. For buttons you will need to add your own OnClientClick to handle client-side events.

Matt Pavey is a Microsoft Certified software developer who specializes in ASP.Net, VB.Net, C#, AJAX, LINQ, XML, XSL, Web Services, SQL, jQuery, and more. Follow on Twitter @matthewpavey

0 comments: