我有 .aspx 页面,该页面通过单击按钮将数据插入数据库。但当我按下按钮时,它就正常了。我收到“成功插入数据”的成功消息。在这种情况下,如果我按“F5”或刷新页面,它将触发按钮单击事件。为什么应该是这样?如何避免这种情况?
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.
恕我直言,最好的方法是使用发布/重定向/获取模式 http://en.wikipedia.org/wiki/Post/Redirect/Get。在您的代码中,在保存数据的位置之后,执行 302 重定向到确认页面:
protected void btnSaveStuff_Click(object sender, EventArgs e)
{
SaveStuffToDatabase();
Response.Redirect("confirmation.aspx");
}
使用该模式时,POST
到原始页面不会最终出现在浏览器历史记录中,刷新结果页面将导致最终结果GET
重复,这应该是安全的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)