Avoiding Duplicate form submission in Asp.net MVC by clicking submit twice

前端 未结 6 1693
情书的邮戳
情书的邮戳 2021-01-30 22:30

I am rendering a form in Asp.net MVC with a submit button. The page redirects after successful record addition into the database. Following is the code :-

[HttpP         


        
6条回答
  •  旧巷少年郎
    2021-01-30 23:04

    I don't think this is quite a duplicate of the answer referenced in the comment, since the link is for spring MVC, and this question is for .NET MVC.

    I actually spent a few hours on this a while back, and came up with the following. This javascript hooks nicely with the unobtrusive jquery validation, and you can apply it to any form that has . Note that it uses jquery 1.7's on function:

    $(document).on('invalid-form.validate', 'form', function () {
        var button = $(this).find(':submit');
        setTimeout(function () {
            button.removeAttr('disabled');
        }, 1);
    });
    $(document).on('submit', 'form', function () {
        var button = $(this).find(':submit');
        setTimeout(function () {
            button.attr('disabled', 'disabled');
        }, 0);
    });
    

    The setTimeouts are needed. Otherwise, you could end up with a button that is disabled after clicked even when client-side validation fails. We have this in a global javascript file so that it is automatically applied to all of our forms.

    Update 16 Nov 2020 by @seagull :

    Replaced selector input[type="submit"] with :submit so it will work with

提交回复
热议问题