Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Form loaded via ajax submits multiple times

I have a partial view containing an ajax form. This partial view is loaded onto my page via an ajax call. I can edit the fields and submit the form and everything works normally. However, if I reload the form N times, the form will submit N times when the save button is clicked.

here is the code for the partial view....

@model blah blah...

<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript</script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"type="text/javascript"></script>

<div id="modalForm">
  @using (Ajax.BeginForm("Edit", "Info", new{id = Model.UserId}, AjaxOptions{OnSuccess = "infoUpdate" }))
  {


       //FORM FIELDS GO HERE

      <input type="submit" value="Save" />


  }
</div>

What am I doing wrong that is causing this behavior?

like image 601
stephen776 Avatar asked Feb 02 '11 00:02

stephen776


4 Answers

Each time you reload the form, a trigger is placed for submitting the form. Thus you have n submitting, if you reload the form n times.

Try to load the form only once, if it's possible.

You can try to unbind the submit trigger, when you click on your submit button:

<input type="submit" value="Save" onClick="submitForm()" />

var submitForm = function() {
    $("#formAddressShipping form").trigger('submit');    
    $("#formAddressShipping form").unbind('submit');
    return false;
};
like image 59
alexl Avatar answered Nov 08 '22 04:11

alexl


Just incase someone is still looking for this - the issue can also occur if you have jquery.unobstrusive js referenced multiple times. For me, I had it in layout and partial. The form got submitted 4 times, may be the field count. Removing the js from partial fixed it. Thanks to this thread ASP.NET AJAX.BeginForm sends multiple requests

like image 26
arc Avatar answered Nov 08 '22 04:11

arc


Moving this jquery.unobtrusive-ajax.js outside partial solved the issue in my case.

like image 26
rns Avatar answered Nov 08 '22 04:11

rns


I have faced the same issue and solved it as follows. I have a list. From that list, I call New, Update, Delete forms in UI Dialog. Success will close dialog and will return to list and update the UI. Error will show the validation message and dialog will remain the same. The cause is AjaxForm is posting back multiple times in each submit click.

Solution:

//Link click from the list -

$(document).ready(function () {
            $("#lnkNewUser").live("click", function (e) {
                e.preventDefault();
                $('#dialog').empty();
                $('#dialog').dialog({
                    modal: true,
                    resizable: false,
                    height: 600,
                    width: 800,
                }).load(this.href, function () {
                    $('#dialog').dialog('open');
                });
            });

//Form submit -
$('#frmNewUser').live('submit', function (e) {
            e.preventDefault();
            $.ajax({
                url: this.action,
                    type: this.method,
                    data: $('#frmNewUser').serialize(),
                    success: function (result) 
                    {
                        debugger;
                        if (result == 'success') {
                            $('#dialog').dialog('close');
                            $('#dialog').empty();
                            document.location.assign('@Url.Action("Index", "MyList")');
                        }
                        else {
                            $('#dialog').html(result);
                        }
                    }
                });

        return false;
    });

The scripts should be in List UI. Not in partial views (New, Update, Delete)

//Partial View -

@model User

@Scripts.Render("~/bundles/jqueryval")

@using (Html.BeginForm("Create", "Test1", FormMethod.Post, new { id = "frmNewUser", @class = "form-horizontal" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    @Html.HiddenFor(model => model.UserID)
<p>@Html.ValidationMessage("errorMsg")</p>
...

}

//Do not use Ajax.BeginForm

//Controller -

    [HttpPost]
    public ActionResult Create(User user)
    {
        if (ModelState.IsValid)
        {
            try
            {
                user.CreatedDate = DateTime.Now;
                user.CreatedBy = User.Identity.Name;

                string result = new UserRepository().CreateUser(user);
                if (result != "")
                {
                    throw new Exception(result);
                }

                return Content("succes");
            }
            catch (Exception ex)
            {
                 ModelState.AddModelError("errorMsg", ex.Message);
            }
        }
        else
        {
            ModelState.AddModelError("errorMsg", "Validation errors");
        }
        return PartialView("_Create", user);
    }

Hope someone get help from this. Thanks all for contributions. Credit to http://forums.asp.net/t/1649162.aspx

like image 39
kma1975 Avatar answered Nov 08 '22 02:11

kma1975