Prevent double-clicking on Button

2019-02-19 06:30发布

问题:

I keep having an issue with users double-clicking on action buttons on my web application, which is meaning duplicate records are being added into my database, and sometimes the user is being charged twice (as the action is being ran twice).

What is the best way of preventing double clicking in ASP.NET?

回答1:

I see you're concerned about this in the face of users without javascript enabled. If that's the case, you need to deal with it on the server side. One idea to deal with this would be to implement CSRF tokens throughout your app.

This basically keeps a token in the server side session, and also requires the token to be submitted in the request. Provided youreset this token in the session in a timely manner (and assuming that you're using usual ASP.Net mechanisms to serialize access to the session), the second request will be using an out of date token, and can be ignored.



回答2:

I think the best solution would be to disable button after clicking using Javascript. Try adding onclick function to it:

<input type="submit" onclick="disable_button(this);" />
<script type="text/javascript>
    function disable_button(sender){
        sender.disabled = true;
    }
</script>

It can also be done using server-side code using server controls. Paste this into your pre-render or page_load event:

yourButton.Attributes.Add("onclick", " this.disabled = true; "+ ClientScript.GetPostBackEventReference(Button1,null)+";");

This will basically disable the Button when ever u click it and then calls the server side code as if the button has been clicked.



回答3:

Have you tried adding a little JavaScript to the submit button?

e.g.
<input type="button" onClick="formSubmit.disabled=true;">

This way the button is disabled right after the first click and won't take the second click ...



回答4:

I solved this problem by using a session variable without enabling or disabling the button. In the Page_Load add :

Session["clicked01"] = "0";

in the btnSave_Click :

if (Session["clicked01"] == "1")
{
    return;
}
/// save the record
Session["clicked01"] == "1"