MVC - 用户双击“提交”按钮时出现问题

MVC - Issue with users double-clicking Submit button

本文关键字:按钮 问题 提交 用户 双击 MVC      更新时间:2023-09-26

我的MVC应用程序中有许多页面,用户单击"提交"按钮即可发布表单。有时用户会单击"提交",由于不会立即执行任何操作,请再次单击它。因此,表格提交两次。为了防止这种情况,我有以下JavaScript代码:

// When the user submits the form, disable the Save button so there is no chance
// the form can get double posted.
$('#form').submit(function () {
    $(this).find('input[type=submit]').prop('disabled', true);
    return true;
});

此代码禁用"提交"按钮,以便用户无法单击两次。这工作正常。但是,如果表单上存在客户端验证错误,则会禁用"提交"按钮,但永远不会发布表单,现在用户无法发布表单。我可以对 JS 代码进行更改以检测是否存在客户端验证错误,如果是,我要么不禁用"提交"按钮,要么重新启用它?

如果您使用的是 jQuery Validate,则可以在禁用按钮之前检查表单是否有效:

$('#form').submit(function () {
    if ($(this).valid()) {
        $(this).find('input[type=submit]').prop('disabled', true);
    }
});

你可以尝试这样的事情:

<button id="subButton" /> <!-- do not use type="submit" because some browsers will automatically send the form -->

Javascript:

$('#subButton').click(function (e) {
    e.preventDefault(); //prevent browser's default behaviour to submit the form
    $(this).prop('disabled', true);
    doValidation();
});
var pTimeout;
function doValidation() {
ajaxLoader.show(); //lock the screen with ajaxLoader
var form = $('#registerForm');
var isPending = form.validate().pendingRequest !== 0; // find out if there are any pending remote requests ([Remote] attribute on model)
if (isPending) {
    if (typeof pTimeout !== "undefined") {
        clearTimeout(pTimeout);
    }
    pTimeout = setTimeout(doValidation, 200); //do the validation again until there are no pending validation requests
}
var isValid = form.valid(); //have to validate the form itself (because form.Valid() won't work on [Remote] attributes, thats why we need the code above
if (!isPending) {
    ajaxLoader.hide();
    if (isValid) {
        $('#registerForm').submit(); //if there are no pending changes and the form is valid, you can send it
    }
    else {
        $('#subButton').prop('disabled', false); //else we reenable the submit button
    }
}};

切换它。

$("input[type='submit']").on("click", function (event) {
   event.preventDefault();
   $(this).prop("disabled", true);
   // perform error checking
   if (noErrors) {
      $("#form").submit();
   }
   else {
      $(this).prop("disabled", false);
   }
});