ASP.NET MVC Form loaded via ajax submits multiple

2019-05-02 12:47发布

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?

6条回答
淡お忘
2楼-- · 2019-05-02 13:08

My first post, faced the same issue

here is the solution which worked for me..

@using (Html.BeginForm("", "", FormMethod.Post, new { enctype = "multipart/form-data", id = "MyForm" }))
{
    //form fields here..
    //don't add a button of type 'submit', just plain 'button' 
    <button type="button" class="btn btn-warning" id="btnSave" onClick="submitForm()">Save</button>  

    <script type="text/javascript">
        var submitForm = function () {
            if ($("#"MyForm").valid())
            { 
                //pass the data annotation validations...                  
                //call the controller action passing the form data..
                handleSaveEvent($("#MyForm").serialize());
            } 
            return false;
        };
    <script>
}
查看更多
地球回转人心会变
3楼-- · 2019-05-02 13:09

Move the jQuery scripts inside the DIV. This seemed to fix the problem.

The tradeoff is that every post will do a get for each script.

查看更多
聊天终结者
4楼-- · 2019-05-02 13:15

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

查看更多
该账号已被封号
5楼-- · 2019-05-02 13:21

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

查看更多
相关推荐>>
6楼-- · 2019-05-02 13:26

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;
};
查看更多
7楼-- · 2019-05-02 13:29

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

查看更多
登录 后发表回答