Search code examples
jqueryajaxgoogle-chromeasp.net-mvc-5ajax.beginform

Ajax.BeginForm not working in chrome MVC 5


I am currently trying to implement an Ajax form in MVC 5.

@using (Ajax.BeginForm("Requirement", "Purchase", null, new AjaxOptions { OnSuccess = "redirectionClick", OnFailure = "Retry", HttpMethod = "POST" }, new { id = "RequirementForm", autocomplete = "off" }))
{
   //Various input fields
   @Html.AntiForgeryToken()
   <input type="submit" value="Submit" class="btn btn-primary EqualSized" id="SubmitBtn" style="width:30%">
   <input type="button" value="Reset" id="Reset" class="btn btn-primary EqualSized" style="width:30%">
}

The functions under script tag:

function CloseModals() {
    $('.modal').modal('hide');
    $('body').removeClass('modal-open');
    $('div.modal-backdrop').remove();
}

function redirectionClick() {
    CloseModals();
    bootbox.alert("Saved Successfully!");
    $.ajax({
        url: "@Url.Action("Requirement", "Purchase")",
        async: false,
        success: function (result) {
            $('#PageData').html(result);
        }
    })
}

function Retry() {
    alert('Unknown Error, Please try submitting the form again!');
    $('#SubmitBtn').attr('disabled', false);
}

$('#SubmitBtn').click(function () {
    if ($('#RequirementForm').valid())
        $(this).attr('disabled', true);
});

And my controller:

[HttpPost]
[ValidateAntiForgeryToken]
public void Requirement(Requirement Details)
{
  //Logic
}

The above code works in FireFox and IE, but not in Chrome. Is there something I am missing in this?


Solution

  • If a submit button is disabled, i don't think it can submit a form, your click handler is firing before your submit handler.

    try changing your click handler to this

    $('#SubmitBtn').click(function () {
        if ($('#RequirementForm').valid())
             $(this).prop('disabled', true).closest('form').submit();
    });
    

    The other way is to handler the submit on the form instead, and disable the button in there if the form is valid. you can use the onbegin or submit event for that