How to avoid the button events on Refresh of page

前端 未结 4 1177
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-09 16:45

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 \" success

4条回答
  •  天命终不由人
    2021-02-09 17:23

    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.

提交回复
热议问题