代码之家  ›  专栏  ›  技术社区  ›  Marcio Gabe

How to submit an ASP.NET MVC form using javascript and still validate on client side?

  •  2
  • Marcio Gabe  · 技术社区  · 14 年前

    I have an ASP.NET MVC 2 form that is working perfectly, doing client side validation (using Data Annotations). Whenever users click on the submit button, client side validation kicks in before the form is actually posted back to the server.

    This is the actual code, really basic stuff:

    <% Html.EnableClientValidation(); %>
    <% using (Html.BeginForm()) { %>
        <%= Html.ValidationSummary(true) %>
        <%: Html.EditorForModel() %>
        <p>
            <input type="submit" value="Save" />
        </p>
    <% } %>
    

    现在我的问题是:我想使用不在<表单></表单>中的按钮提交表单,就像上面示例中的按钮一样。此按钮需要放置在页面上单独的<Div>中,该页面的工作方式类似于我的应用程序中所有按钮和操作的工具栏。

    I'm able to submit the form using something like this (using jQuery):

    <asp:Content ID="Content2" ContentPlaceHolderID="ToolBarContent" runat="server">
        <input type="submit" value="Save" onclick="$('#form0').submit();" />
    </asp:Content>
    

    The only problem is that this will not trigger the client side validation, as if the user was clicking in the normal submit button. The whole form is posted back, server side validation is performed and the view is rendered again showing the validation errors.

    我不想把这个常规的提交按钮和表单放在一起,只需要在工具栏中有这个按钮,那么有什么方法可以做到这一点呢?单独的按钮调用表单的提交,同时仍触发表单的客户端验证?

    4 回复  |  直到 14 年前
        1
  •  2
  •   Darin Dimitrov    14 年前

    试试这个黑客:

    <input type="submit" value="Save" onclick="$('#dummy').click();" />
    

    哪里 dummy 是隐藏的 submit 在你的窗体内的按钮。

    Save button doesn't need to be a 提交 按钮,如果它未放置在 form .

        2
  •  0
  •   Matthew Abbott    14 年前

    验证方法附加到表单的Submit事件,这意味着您应该能够从JavaScript调用Form.Submit(),并且Submit事件仍然应该启动。

        3
  •  0
  •   Chad Moran    14 年前

    您可以尝试jquery的Ajax表单插件。

    http://jquery.malsup.com/form/

    您也可以通过附加到表单的提交事件 $('#form').submit(function() { })

        4
  •  0
  •   Gregoire    14 年前

    尝试 $("#yourform").validate("submit"); 如果您使用microsoftmvcvalidation.js 或 $("#yourform").validate() 如果使用jquery.validate.js