Html.BeginForm如何避免多个表单提交?

时间:2014-09-23 09:18:14

标签: javascript asp.net asp.net-mvc forms asp.net-mvc-validation

我们有以下注册页面代码

@using (Html.BeginForm(MVC.Account.Register(Model.ReturnUrl), FormMethod.Post, new { @id = "register-form" }))
{
    <div class="control-group clear">
        @Html.LabelFor(m => m.Email)
        @Html.TextBoxFor(m => m.Email, new { type = "email", @class = "forbid-lt-gt" })
        <span class="hint raise">Will be user as Username.</span>
        <div class="error">@Html.ValidationMessageFor(m => m.Email)</div>
    </div>
    <div class="control-group clear">
        @Html.LabelFor(m => m.Password)
        @Html.PasswordFor(m => m.Password)
        <span class="hint raise">Length between 6 and 10 characters</span>
        <div class="error">@Html.ValidationMessageFor(m => m.Password)</div>
    </div>
    <div class="control-group clear">
        @Html.LabelFor(m => m.ConfirmPassword)
        @Html.PasswordFor(m => m.ConfirmPassword)
        <div class="error">@Html.ValidationMessageFor(m => m.ConfirmPassword)</div>
    </div>

    <div class="control-group action">
        <button class="btn primary" type="submit">
            <span>Sign up</span>
        </button>
    </div>
    <div class="clear"></div>
}

文件formBlocker.js可防止多个按钮点击

$(function() {
    $('form').one('submit', function () {
        $(this).find('button[type="submit"]').attr('disabled', 'disabled');
    });

    //Enable submit button if data has changed
    $('form').live("input", function () {
        $(this).find('button[type="submit"]').removeAttr('disabled');
    });
});

通常一切都很好,但有时它不起作用,用户在按钮上多次点击后,表格可以多次发送到服务器。早期我们发现在IE表单中单击提交按钮后两次发送到服务器。现在我们没有这个问题但是没有解决。

2 个答案:

答案 0 :(得分:2)

live已经死了。死。它在2.7中被弃用,在2.9中删除。 DEAD!

我会用这种方法:

var serializedData;

$(function () {
    $('form').submit(function () {
        var tempSerializedData = $(this).serialize();
        if (tempSerializedData != serializedData) 
            serializedData = tempSerializedData;
        else 
            return false;

    });
});

答案 1 :(得分:2)

试试这个不确定,但这对我有用

$('form').one('submit', function () {
        $(this).find('button[type="submit"]').attr('disabled', 'disabled');
        setTimeout(function () {
              $(this).find('button[type="submit"]').attr('disabled', 'disabled');
         }, 20);
    });