Button click event called again when page is refreshed using F5

I found that if you press F5 or refresh from browser window, the last event fires again. For ex. I have clicked on a button the button event is carried out normally, but if i press F5 from browser window then the same event is fired again.

Could someone have any idea?

Thanks for sharing your valuable time.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

As per NinenthSense, thats how the browser reacts when the user refresh the page.

If you still want to restrict you can go for some javascript like below

//to avaoid pressing F5 key

document.onkeydown = function()
 {
          if(event.keyCode==116) {
          event.keyCode=0;
          event.returnValue = false;
          }
}

//to avoid refresh, using context menu of the browser

document.oncontextmenu = function() {event.returnValue = false;}

Method 2

If you want to totally flush the page after a postback occurs so that it doesn’t fire again, you can Response.Redirect to the same page.

Response.Redirect(Request.Url.AbsoluteUri);

That basically takes your entire querystring and sends the browser back to it, clearing out any Posts in the process. I often do that after a Save() routine to get the page back to a “normal” state. This works nicely too if your Save routine is updating a database, and you’ve got some UI elements on the page that read from the database, then you don’t have to worry about re-loading those elements with the fresh data.

Also, you can add an Extension method to hit this quickly like so:

public static class Extensions
{
    public static void Reload(this Page page)
    {
        page.Response.Redirect(page.Request.Url.AbsoluteUri);
    }
}

You then call this method in your code like so:
private void SaveCrap() 
{
    SavemeBlahBlah(); // save to dbase
    this.Page.Reload(); 
}

Method 3

It is not a bug. It is by design.

When you press F5/Refresh, it sends the same request to server again.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x