简体   繁体   中英

How can I run a event handler before Page.IsPostBack

I want to run code in a button event handler but the if(Page.IsPostBack) conditional is running first and contains a redirect so the event never runs.

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        (do some stuff with save button pressed...)

        // then return the same page to prevent another post on refresh 
        Response.Redirect(Request.Url.AbsoluteUri);
    }
}

and on that page there is another button that calls a handler:

protected void Export_Click(object sender, EventArgs e)
{ 
    (do other stuff..)
}

Is there a way to run the handler first or a way to check which button was clicked so I can add a conditional to the redirect? Thanks.

This behavior is actually by design in WebForms. To keep things stateless, a full postback occurs whenever you wish to fire off a server-side event.

So the short answer is no, you cannot force your event to occur before the Page_Load does.

However, you can restructure your design a bit to get the behavior you desire. At the moment, it looks as though you are depending on a PostBack having a occurred to execute your save logic. Instead of handling the logic in your Page_Load event, it could be handled in an event appropriate to how your user is expecting to save.

If saving is triggered through a button press, then moving logic for handling the save and redirect to a Save_Click event will allow other events related to PostBack to execute their own logic as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM