How do I prevent users clicking a button twice?

2020-01-24 04:04发布

I have an old ASP.NET web forms application (.NET 2.0) that has a process that takes 30 seconds or so to run when a button is clicked. I need to prevent the button from being clicked twice. This will prevent posting twice, which causes duplicate data in a database.

I tried adding;

OnClientClick="this.disabled='true';"

to try to disable the button in JavaScript. However, though the button becomes disabled, the postback for the button then doesn't work.

Disabling the button to prevent multiple submissions is the ideal for this application. How can I do this?

EDIT

I am unable to use third-party controls.

15条回答
啃猪蹄的小仙女
2楼-- · 2020-01-24 04:34

You need to also set the Button's UseSubmitBehavior property to false.

Web browsers do not include disabled elements in a form's POST data, even if the element happens to be the button that triggered the form submission in the first place. Unfortunately, ASP.NET WebForms' single-form-page design relies on that bit of information to know which control raised the PostBack and which event handler to execute (i.e. Button1.On_Click).

Switching to UseSubmitBehavior="false" injects a __doPostBack('Button1', '') in the client-side onclick handler to work around that problem. Then, even if you disable the Button, the __doPostBack parameter lets ASP.NET know which control raised the PostBack and which events to fire on the server-side.

查看更多
仙女界的扛把子
3楼-- · 2020-01-24 04:34

Advantages

  • Works out of the box for all buttons
    • Even buttons that did not trigger the submit will be disabled.
    • LinkButtons will also be disabled.
  • Works with UpdatePanels (ie, partial and asynchronous postbacks)
  • Works for full postbacks
  • Won't disable buttons when validation prevents postback
  • Button press, enter-key press and AutoPostBack events will cause buttons to become disabled

Limitations

† Most other solutions I have seen have these same limitations

  • Relies on jQuery
  • Only works for ASP forms
  • If the user clicks the browser's cancel button after submission, the user will not be able to submit again and may get confused.
  • There remains other ways that a user could initiate a postback:
    • Submit using the enter key
    • Autopostback events

Code

Simply place this snippet at the bottom of your HTML code before the closing </body> tag.

<script type="text/javascript">
    jQuery(function ($) {

        /*
         * Prevent Double Submit
         * ---------------------
         * Disables submit buttons during form submission and asp async postbacks
         */

        // class name assigned to disabled :submit elements
        var disabledClass = 'asp-postback-disable';

        // selector for buttons and other elements that may cause a postback
        var submittableSelector = [
            'a[href^="javascript:__doPostBack"]',
            ':submit'
        ].join(",");

        // returns false; used to prevent event bubbling
        function returnFalse() { return false; }

        // logs errors
        function error(ex) {
            if (typeof console === 'object' && console.error != null) {
                console.error('Prevent Double Submit Error:', ex);
            }
        }

        // disables :submit elements
        function disableSubmit() {
            try {
                $(submittableSelector, 'form')
                    .addClass(disabledClass)
                    .on('click.asp-postback-disable', returnFalse);
            }
            catch (ex) { error(ex); }
        }

        // enables :submit elements
        function enableSubmit() {
            try {
                $('.asp-postback-disable,' + submittableSelector, 'form')
                    .removeClass(disabledClass)
                    .off('click.asp-postback-disable', returnFalse);
            }
            catch (ex) { error(ex); }
        }

        // Handle async postbacks
        if (typeof Sys === 'object') {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            prm.add_beginRequest(function (s, e) { disableSubmit(); });
            prm.add_endRequest(function (s, e) { enableSubmit(); });
        }
        else {
            error('Sys is undefined.');
        }

        // Handle navigation (eg, Full postback)
        $(window).bind('beforeunload', function (e) {
            disableSubmit();
        });

    });
</script>

<style type="text/css">
    .asp-postback-disable { opacity: 0.25; }
</style>
查看更多
冷血范
4楼-- · 2020-01-24 04:36

Most of this solutions provided above that suggest disabling won't work because you won't get a PostBack. This is the simplest and cleanest working solution I've seen:

OnClientClick="if(this.value === 'Saving...') { return false; } else { this.value = 'Saving...'; }"
查看更多
看我几分像从前
5楼-- · 2020-01-24 04:36

In the Page_Load event of your form put this line:

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

Source: dotnetodyssey.com

查看更多
老娘就宠你
6楼-- · 2020-01-24 04:38

I found that link very useful to solve this problem Disable ASP.Net button after click to prevent double clicking

I hope that can help :)

查看更多
Juvenile、少年°
7楼-- · 2020-01-24 04:42

I usually add this method to my BasePage for reuse.

This code handle validations too

/// <summary>
///  Avoid multiple submit
/// </summary>
/// <param name="button">The button.</param>
/// <param name="text">text displayed on button</param>
public void AvoidMultipleSubmit(Button button,string text="wait..." )
{
    Page.ClientScript.RegisterOnSubmitStatement(GetType(), "ServerForm", "if(this.submitted) return false; this.submitted = true;");
    button.Attributes.Add("onclick", string.Format("if(typeof(Page_ClientValidate)=='function' && !Page_ClientValidate()){{return true;}}this.value='{1}';this.disabled=true;{0}",
        ClientScript.GetPostBackEventReference(button, string.Empty),text));
}
查看更多
登录 后发表回答