views:

260

answers:

5

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?

+1  A: 

not sure, but I think you are looking for..

if (Page.IsPostBack)
    { 
    }
Muhammad Akhtar
I want to do some manipulations before a postback is served. Not after the postback has happened. Hope you get it.
NLV
+1  A: 

Page.IsPostBack is your friend.

Saar
I want to do some manipulations before a postback is served. Not after the postback has happened. Hope you get it.
NLV
+2  A: 

You can check for a postback in one of the page events for your form.

If you want to take some action on postback that involves creating controls or manipulating viewstate then you may want to come in on an earlier event like Page_Init.

Try this:

protected void Page_Init(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            //Check for your conditions here, 

            if (Page.IsAsync)
            {
                //also you may want to handle Async callbacks too:
            }
        }
    }
Tj Kellie
I want to do some manipulations before a postback is served. Not after the postback has happened. Hope you get it.
NLV
+2  A: 

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

slugster
Thanks for the link.
NLV
+5  A: 

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.

womp
Perfect! Worked exactly the way i want.
NLV