ASP.NET MVC - How to prevent double click submit with jquery.validate.unobtrusive lib?

后端 未结 9 1150
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 07:47

I need to avoid the double click submitting behavior. I\'m using the client validation with the unobtrusive library. I have the following code for avoiding the double clic:<

9条回答
  •  -上瘾入骨i
    2020-12-29 07:59

    Based on Ryan P's popular answer I created the following generic solution that also works with my ajax form.

    decorate your custom submit button with the following class:

    
    

    Add the following to your javascript file:

    function OneClickSubmitButton() {
        $('.one-click-submit-button').each(function () {
            var $theButton = $(this);
            var $theForm = $theButton.closest('form');
    
            //hide the button and submit the form
            function tieButtonToForm() {
                $theButton.one('click', function () {
                    $theButton.hide();
                    $theForm.submit();
                });
            }
    
            tieButtonToForm();
    
            // This handler will re-wire the event when the form is invalid.
            $theForm.submit(function (event) {
                if (!$(this).valid()) {
                    $theButton.show();
                    event.preventDefault();
                    tieButtonToForm();
                }
            });
        });
    }
    
    OneClickSubmitButton();
    

    since this is an ajax form we want to reload the handlers if we fail server validation.

    function MyForm_OnSuccess() {
        if (true if your form passed validation logic) {
            //do something since your form submitted successfully
        } else { //validation failed on server
            OneClickSubmitButton(); //reinitialize the button logic
        }
    }
    

    Obviously if you don't have ajax forms you can omit the whole OneClickSubmitButton function business and run $('.one-click-submit-button').each(... directly.

提交回复
热议问题