WearySky
WearySky

Reputation: 107

ASP.Net Response.Redirect is ignored in button handler if refresh is pressed?

Ok, I've got a particularly confusing problem, and I'm not sure what my best option is for fixing it. I have an asp.net page with a button on it, and the handler for the button can (for reasons outside my immediate control/ability to fix) occasionally take a while to complete. At the end of the handler, I've got a Response.Redirect call. If the user hits Refresh while the button handler is running, it will finish running the handler for the button press (good) but then reload the page, instead of handling the Response.Redirect.

It took me FOREVER just to figure out that this is what was happening, but once I figured that out, I was able to reproduce it in some really super simple sample code. I created a new C# .Net web project in VS 2010 (targeted to .Net 4), added a button to the home page:

<asp:button id="btnSubmit" runat="server" OnClick="btnSubmit_Click" text="Submit"/>

and then added the handler code to just sleep for 10 seconds (to give me time to hit refresh):

protected void btnSubmit_Click(object sender, EventArgs e)
{
    Thread.Sleep(10000);
    Response.Redirect("about.aspx");
}

And sure enough - if I let the button handler run, it redirects fine (obviously, as expected), but if I hit refresh during that 10 second Thread.Sleep, the response.Redirect gets ignored.

I need to figure out a way to force that Response.Redirect to get obeyed. I have a feeling I have to just handle it in the Page_Load event that gets triggered by the user hitting Refresh (ie having a session variable that gets created, like a "handling_button" or something that I check for and just redirect if it's detected on page load, that gets removed when I get to the Redirect location), but I'm hoping there's something that I'm missing out here that's a bit more elegant.

Upvotes: 0

Views: 979

Answers (1)

recursive
recursive

Reputation: 86064

When you hit f5, it instructs the browser to abandon the current page, and make a new request for the current address.

I don't think there is a clean solution for what you are trying to do.

javascript has the window.onbeforeunload property, but I don't think that will work here, because at the time the reload is requested, a navigation event has already been initiated.

It seems the only solution will be to have a test in your original page that will detect whether the request has been made yet or not.

It may help the users' perception to use a javascript event handler on the form submission to show a spinner too.

Upvotes: 1

Related Questions