Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept any postback in a page? - ASP.NET

I want to intercept any postbacks in the current page BEFORE it occurs . I want to do some custom manipulation before a postback is served. Any ideas how to do that?

like image 859
NLV Avatar asked Feb 10 '10 05:02

NLV


4 Answers

There's a couple of things you can do to intercept a postback on the client.

The __doPostBack function looks like this:

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

Notice that it calls "theForm.onsubmit()" before actually doing the postback. This means that if you assign your form an onsubmit javascript function, it will always be called before every postback.

<form id="form1" runat="server" onsubmit="return myFunction()">

Alternately, you can actually override the __doPostBack function and replace it with your own. This is an old trick that was used back in ASP.Net 1.0 days.

var __original= __doPostBack;
__doPostBack = myFunction();

This replaces the __doPostBack function with your own, and you can call the original from your new one.

like image 150
womp Avatar answered Nov 02 '22 15:11

womp


Use the following options

All options works with ajax-enabled-forms and simple forms.
return false to cancel submit within any submit-handler.

Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "submit-handler", "alert(\"On PostBack\");");

Equivalent javascript --don't use this code with previous code simultaneously

// Modify your form tag like this
<form onsubmit="javascript:return submit_handler();" ...>

// Add this script tag within head tag
<script type="text/javascript">
    function submit_handler() {
        // your javascript codes
        // return false to cancel
        return true; // it's really important to return true if you don't want to cancel
    }
</script>

And if you want complete control over __doPostBack put this script next to your form tag

<script type="text/javascript">
    var default__doPostBack;
    default__doPostBack = __doPostBack;
    __doPostBack = function (eventTarget, eventArgument) {
        // your javascript codes
        alert('Bye __doPostBack');
        default__doPostBack.call(this, eventTarget, eventArgument);
    }
</script>

Tested with ASP.NET 4.0

like image 28
Beygi Avatar answered Nov 02 '22 13:11

Beygi


To get the postback before a page does, you can create an HttpHandler and implement the ProcessRequest function.

Check this Scott Hanselman link for a good blog post on how to do it (including sample code).

like image 44
slugster Avatar answered Nov 02 '22 14:11

slugster


Page.IsPostBack is your friend.

like image 1
Saar Avatar answered Nov 02 '22 13:11

Saar