【问题标题】:ASP.NET MVC Form loaded via ajax submits multiple times通过 ajax 加载的 ASP.NET MVC 表单多次提交
【发布时间】:2011-02-02 00:32:42
【问题描述】:

我有一个包含 ajax 表单的局部视图。此部分视图通过 ajax 调用加载到我的页面上。我可以编辑字段并提交表单,一切正常。但是,如果我重新加载表单N次,单击保存按钮时表单将提交N次。

这里是局部视图的代码......

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

我做错了什么导致这种行为?

【问题讨论】:

  • 嗯,我认为这很明显......我该如何解决这种奇怪的行为?
  • 每次加载它时,我都会对返回上述部分视图的控制器操作进行 ajax 调用,并将其加载到页面上的 div 中...

标签: c# asp.net-mvc asp.net-mvc-3 razor


【解决方案1】:

每次重新加载表单时,都会放置一个触发器来提交表单。因此,如果您重新加载表单 n 次,则您有 n 次提交。

如果可能,请尝试仅加载一次表单。

当您点击提交按钮时,您可以尝试取消绑定提交触发器:

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

var submitForm = function() {
    $("#formAddressShipping form").trigger('submit');    
    $("#formAddressShipping form").unbind('submit');
    return false;
};

【讨论】:

  • 这似乎是最可能的原因。我会试一试并报告
  • 这是我遇到的相同问题的解决方案。谢谢。
【解决方案2】:

以防有人仍在寻找这个问题 - 如果您多次引用 jquery.unobtrusive js,也会出现此问题。对我来说,我有它的布局和部分。表单提交了4次,可能是字段数。从部分中删除 js 修复它。感谢这个帖子ASP.NET AJAX.BeginForm sends multiple requests

【讨论】:

    【解决方案3】:

    将这个 jquery.unobtrusive-ajax.js 移到部分外部解决了我的问题。

    【讨论】:

      【解决方案4】:

      我遇到了同样的问题并解决了如下。我有一个清单。从该列表中,我在 UI Dialog 中调用 New、Update、Delete 表单。成功将关闭对话框并返回列表并更新 UI。错误将显示验证消息,对话框将保持不变。原因是 AjaxForm 在每次提交点击中多次回发。

      解决方案:

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

      脚本应该在列表 UI 中。不在部分视图中(新建、更新、删除)

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

      希望有人能从中得到帮助。感谢大家的贡献。 感谢http://forums.asp.net/t/1649162.aspx

      【讨论】:

      • 非常感谢,我希望我早点找到这个!浪费了几个小时试图理解为什么我的表单多次提交并且效果很好。
      【解决方案5】:

      在 DIV 中移动 jQuery 脚本。这似乎解决了问题。

      权衡是每个帖子都会为每个脚本执行一次获取。

      【讨论】:

        【解决方案6】:

        我的第一篇文章,遇到了同样的问题

        这是对我有用的解决方案..

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-16
          • 2011-05-27
          • 1970-01-01
          • 2015-05-17
          • 2016-02-29
          • 1970-01-01
          相关资源
          最近更新 更多