Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Executing a event or function on each postback

0.00/5 (No votes)
5 Apr 2012 1  
Executing a event or function on each postback

Introduction

Executing a event or function on each postback

Background

Problem: Suppose we want to call an javascript function or an event on each postback eg. show a loading image on each every postback. Using jQuery we can bind a function on form submit. However, it will only work with buttons and input type submit. This will fail when an auto postback occurs or postback occurs through some linkbutton.

Asp.net performs each postback using a javascript function which it inserts in its one and only one form tag. So we will be tweaking this function for our own purpose

Using the Code

  <script type="<a class="attribute-value">text/javascript">
 <![CDATA[
    var theForm = document.forms['form1'];
    if (!theForm) {
      theForm = document.form1;
  }
   function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
  }
]]>
</script>

Above code is what inserted by ASP.net engine.

 function doSomething() {----};

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;         
        doSomething();
        theForm.submit();
    }
  }

We will insert our own __doPostBack function at end of form tag so that javascript engine overrides the previous one.

 <form > --code by ASP.net ---   page content---      --- modified script--- </form>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here