Saturday, 19 January 2019

Multiple Submit Modal Bootstrap in MVC 5

I have btnAdd button which will load partial view into bootstrap modal like this :

$('#btnAdd').click(function (event) {
    event.preventDefault();
    var url = $(this).attr("href");
    $.get(url, function (data) {
        $('#addContainer').html(data);

        $.getScript("/Scripts/jquery.unobtrusive-ajax.min.js");
        $.getScript("/Scripts/jquery.validate-vsdoc.js");
        $.getScript("/Scripts/jquery.validate.js");
        $.getScript("/Scripts/jquery.validate.min.js");
        $.getScript("/Scripts/jquery.validate.unobtrusive.js");
        $.getScript("/Scripts/jquery.validate.unobtrusive.min.js");

        $('#addModal').modal('show');
    });
});

and the partial view loaded like this :

@using (Ajax.BeginForm("Create", "MasterBanks", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp", OnSuccess = "CreateSuccess" }))
{
    @Html.AntiForgeryToken()
    ....
}

and CreateSuccess which handle the success form :

function CreateSuccess(data) {
    if (data !== "success") {
        $('#addContainer').html(data);
        return;
    }
    $('#addModal').modal('hide');
    $('#addContainer').html("");

    var grid = new MvcGrid(document.querySelector('#data-table'));
    grid.reload();
}

The problem is when I click the button, every time I open the modal whether is success or not, or just open the modal and close again without submitting the form. Next time I submit the form, the data will be posted several times just like how many I open the modal.

If I delete the $.getScript, the problem does not occurred.

$.getScript("/Scripts/jquery.unobtrusive-ajax.min.js");
$.getScript("/Scripts/jquery.validate-vsdoc.js");
$.getScript("/Scripts/jquery.validate.js");
$.getScript("/Scripts/jquery.validate.min.js");
$.getScript("/Scripts/jquery.validate.unobtrusive.js");
$.getScript("/Scripts/jquery.validate.unobtrusive.min.js");

Why I am using that $.getScript? Because remote validating just working after the form loaded. Why I am not load it in partial view? I got some warning XMLHttpRequest Deprecated when load it inside partial view, and after browsing some articles, this solution works for this warning but created another problem.

I have tried add some script when click the btnAdd before bind the data : $('#addContainer').html(""); OR $('#addContainer').empty(); or $('#addModal').data('modal',null); and some others, but none of them is working.

I tried with unbind() also but not working, it still return multiple submit. Look like the javascipt not unloaded when the modal closed like if I put the script inside partial view.



from Multiple Submit Modal Bootstrap in MVC 5

No comments:

Post a Comment