Arnold_Brhen
Arnold_Brhen

Reputation: 95

Html.BeginForm how to avoid multiple form submission?

We have the following code for registration page

@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>
}

And the file formBlocker.js to prevent multiple button click

$(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');
    });
});

Usually all is fine, but sometimes it doesn't work and after user clicks several times on button the form can be sent several times to server. Early we had issue that after a click on submit button in IE form was sent to server twice. Now we don't have this issue but it was't fixed.

Upvotes: 1

Views: 1748

Answers (2)

sangram parmar
sangram parmar

Reputation: 8736

Try this Not sure but this is working for me

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

Upvotes: 2

gdoron
gdoron

Reputation: 150303

live is dead. dead. It was deprecated in 2.7 and removed in 2.9. DEAD!

I would use this approach:

var serializedData;

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

    });
});

Upvotes: 2

Related Questions