简体   繁体   English

通过ajax加载的ASP.NET MVC表单多次提交

[英]ASP.NET MVC Form loaded via ajax submits multiple times

I have a partial view containing an ajax form. 我有一个包含ajax表单的局部视图。 This partial view is loaded onto my page via an ajax call. 这个局部视图通过ajax调用加载到我的页面上。 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. 但是,如果我重新加载表单N次,单击保存按钮时表单将提交N次。

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? 我做错了导致这种行为的原因是什么?

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. 因此,如果您重新加载表单n次,则必须提交。

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

将此jquery.unobtrusive-ajax.js移到局部外部解决了我的问题。

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. 从该列表中,我在UI对话框中调用新建,更新,删除表单。 Success will close dialog and will return to list and update the UI. 成功将关闭对话框并返回列表并更新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. 原因是AjaxForm在每次提交点击中多次回发。

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. 脚本应该在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 感谢http://forums.asp.net/t/1649162.aspx

Just incase someone is still looking for this - the issue can also occur if you have jquery.unobstrusive js referenced multiple times. 只是因为有人仍在寻找这个问题 - 如果你多次引用jquery.unobstrusive js也会出现这个问题。 For me, I had it in layout and partial. 对我来说,我有布局和部分。 The form got submitted 4 times, may be the field count. 表格提交了4次,可能是现场统计。 Removing the js from partial fixed it. 从部分固定它删除js。 Thanks to this thread ASP.NET AJAX.BeginForm sends multiple requests 感谢这个线程ASP.NET AJAX.BeginForm发送多个请求

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

Move the jQuery scripts inside the DIV. 将dQuery脚本移动到DIV中。 This seemed to fix the problem. 这似乎解决了这个问题。

The tradeoff is that every post will do a get for each script. 权衡是每个帖子都会为每个脚本做一个get。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM