Button click event called again when page is refreshed using F5

安稳与你 提交于 2019-11-28 02:16:19

问题


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.


回答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;}



回答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(); 
}



回答3:


It is not a bug. It is by design.

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



来源:https://stackoverflow.com/questions/1558790/button-click-event-called-again-when-page-is-refreshed-using-f5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!