Click here to Skip to main content
15,881,173 members
Articles / Web Development / ASP.NET
Tip/Trick

Executing a event or function on each postback

Rate me:
Please Sign up or sign in to vote.
2.00/5 (1 vote)
5 Apr 2012CPOL 23.1K   1   3
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

JavaScript
  <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.

C++
 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.

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

License

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


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionjQuery: to bind the code to our form Pin
ericpxz5-Apr-12 4:24
ericpxz5-Apr-12 4:24 
AnswerRe: jQuery: to bind the code to our form Pin
Laserson5-Apr-12 18:02
Laserson5-Apr-12 18:02 
GeneralRe: jQuery: to bind the code to our form Pin
ericpxz5-Apr-12 23:05
ericpxz5-Apr-12 23:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.