How to avoid the button events on Refresh of page

拜拜、爱过 提交于 2019-12-21 02:25:30

问题


I have .aspx page that page inserts the data to the database on a button click. But when i press the button it is going right. i m getting the Successfully message as " successfully inserted data". In this situation if i press "F5" or Refresh the page it is firing the button click event. Why it should be ? How to avoid this condition ?


回答1:


When the user clicks F5 (or uses a toolbar button to refresh the page) it will cause a new request, identical to the previous one, to be sent to the server. The Button.Click event will be raised again, but you have a few ways to protect yourself against inserting the data twice.

The best way, IMHO, is to use the Post/Redirect/Get pattern. In your code, right after the point where the data is saved, do a 302 redirect to a confirmation page:

protected void btnSaveStuff_Click(object sender, EventArgs e)
{
    SaveStuffToDatabase();
    Response.Redirect("confirmation.aspx");
}

When using the pattern, the POST to the original page will not end up in the browser history, and refreshing the result page will cause the final GET to be repeated, which should be safe.




回答2:


Add this in your class:

#region Browser Refresh
private bool refreshState;
private bool isRefresh;

protected override void LoadViewState(object savedState)
{
    object[] AllStates = (object[])savedState;
    base.LoadViewState(AllStates[0]);
    refreshState = bool.Parse(AllStates[1].ToString());
    if (Session["ISREFRESH"] != null && Session["ISREFRESH"] != "")
        isRefresh = (refreshState == (bool)Session["ISREFRESH"]);
}

protected override object SaveViewState()
{
    Session["ISREFRESH"] = refreshState;
    object[] AllStates = new object[3];
    AllStates[0] = base.SaveViewState();
    AllStates[1] = !(refreshState);
    return AllStates;
}

#endregion 

And in your button click do this:

protected void Button1_Click(object sender, EventArgs e)
{
    if (isRefresh == false)
    {
        Insert Code here



回答3:


Add a update panel and set the Update Mode of the update panel as Conditional. This worked for me!!




回答4:


The refresh will re-submit the form you posted last time when you clicked the button.

Usually, when you refresh a page you think of GETing the page again, or doing an HTTP GET, but since the last thing you did was a POST (when you clicked the submit button) the browser will perform the post again to attempt to invoke the same response.

I suggest using the Post/Redirect/Get pattern as suggested by Jorn Schou-Rode.

This article also seems relevant. http://aspalliance.com/687_Preventing_Duplicate_Record_Insertion_on_Page_Refresh



来源:https://stackoverflow.com/questions/2167490/how-to-avoid-the-button-events-on-refresh-of-page

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