问题
I have a button that has click event in my C#. This works great. However afetr pressing F5 to refresh the page I noticed the button event is fired. This occurs every time I click F5. I've added if(page.IsPostBack) and the method still runs.
Is there any way to stop this method from firing when the F5 Refresh button is clicked?
Thanks!
http://pastebin.com/9ycNraaT
回答1:
If you have a page that needs to be run once, you should implement logic in your code that prevents the same method from running multiple times. In pseudo-code:
if (canExecuteMethod()) {
executeMethod();
} else {
displayMessageThatMethodCannotBeExecuted();
}
For example, you can check a Session variable with canExecuteMethod()
, which returns false when it is not present and is set in executeMethod()
:
function canExecuteMethod() {
return Session["methodIsExecuting"] == null
|| Session["methodIsExecuting"] == false;
}
function executeMethod() {
Session["methodIsExecuting"] = true;
// ...
}
Of course the use of a Session variable has it limits, so you might want to consider using a database or AppSettings variable instead.
回答2:
try to use Response.Redirect("Your page ")
after the your add/update code. it isn't good practice, but it will help you.
回答3:
if(!page.IsPostBack)
NOT if(page.IsPostBack)
回答4:
No way. If once you click button (and post data) after refresh the same data will be sended.
来源:https://stackoverflow.com/questions/5484000/asp-net-stop-button-event-running-on-refresh