Avoiding Duplicate form submission in Asp.net MVC by clicking submit twice
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 <input type="submit"
. 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 <button type="submit" />
as well
The solution for mvc applications with mvc client side validation should be:
$('form').submit(function () {
if ($(this).valid()) {
$(':submit', this).attr('disabled', 'disabled');
}
});