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?
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.
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
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).
Page.IsPostBack is your friend.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With