【问题标题】:Is it possible to pass event to an OnBegin function of an Ajax form?是否可以将事件传递给 Ajax 表单的 OnBegin 函数?
【发布时间】:2017-02-06 03:45:08
【问题描述】:

我的应用程序中有一个 Ajax 表单。我想将事件传递给 OnBegin 函数,然后使用 event.preventdefault() 这将阻止表单提交,然后检查某些条件我正在尝试提交表单手动。但它不起作用,我无法弄清楚原因。

Ajax.BeginFrom:

   @using (Ajax.BeginForm("Update", "Project", false, new AjaxOptions { InsertionMode = InsertionMode.Replace,
                                                                         HttpMethod = "Post",
                                                                         OnBegin = "return OnBeginForm(event);",
                                                                         OnSuccess = "OnSuccessArtwork(data);", 
                                                                         OnFailure = "OnFailureArtwork(data);" }, 
                                                                         new { id = "Ajax_form" }))
{
   // Here I have all the form elements //
  <input type="submit" id="btnUpdate" class="btn02 pull-left" value="Update"/> 
}

OnBegin 函数:

function OnBeginForm(e) {
   e.preventDefault();
   if(some condition){
     $('#Ajax_form').submit();
   }
   else{
     return false;
   }
}

【问题讨论】:

    标签: javascript jquery asp.net-mvc forms ajax.beginform


    【解决方案1】:

    event.preventdefault() 将阻止表单提交

    你也可以使用return false;来阻止表单提交,它基本上做到了event.preventdefault()的效果。 检查this

    下面的脚本应该适合你:

    function OnBeginForm() {
    
        if (some condition) {
          return false;
        }
    
    }
    

    希望有帮助:)

    Reference

    【讨论】:

    • 我们无法触发提交。这将导致无限循环,而我们将不得不使用on('submit') 手动提交表单。无论如何,谢谢,我这边 +1。
    • @JibinBalachandran,你在调试时遇到过无限循环吗?
    • 这将创建一个无限循环,因为$('Ajax_form').trigger('submit'); 触发提交事件,该事件又调用OnBeginForm() 触发提交事件,该事件调用OnBeginForm() 触发.....
    • 如果return false;这行代码被执行,那么提交将被取消。 (但话虽如此,当您使用$.ajax() 方法获得更大的灵活性和更好的性能时,我永远无法理解为什么用户要使用AjaxBegin()(甚至不再受支持))
    • @JibinBalachandran,因为e不是提交事件(实际上它已经被插件取消了)
    【解决方案2】:

    我找到了更好的解决方案....

        $('input[type=submit]').on('click', function (e) {
            e.preventDefault();
            var buttonid = $(this).attr('id');
            if (buttonid == "btnUpdate") {
                //Do what ever you want it fires before Ajax Submit
                 //Finaly ajax submit manually trigger submit event
                 $(this).trigger('submit');
            }
    
    
        });
    

    【讨论】:

      猜你喜欢
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多