MVC 2 jQuery验证和ajax表单

时间:2022-12-01 10:23:06

I want to use jQuery ($.post) to submit my html form, but I want to use the client side validation feature of MVC 2. Currently I hook up the post function to the "OnSubmit" event of the form tag, but I can't hook into the validation, ideally I want to be able to do

我想使用jQuery($ .post)来提交我的html表单,但我想使用MVC 2的客户端验证功能。目前我将post函数连接到表单标签的“OnSubmit”事件,但我无法挂钩验证,理想情况下我希望能够做到

if (formIsValid) {
     $.post('<%=Url.Action("{some action}")%>'...
}

Please note, Client side validation is working with jQuery.validation, I just can't get it to test if the validation was successful or not before I post my data.

请注意,客户端验证正在使用jQuery.validation,在发布数据之前,我无法测试验证是否成功。

Andrew

The final solution

最终的解决方案

<%
    Html.EnableClientValidation();
    using (Html.BeginForm("Register", "Account", FormMethod.Post, new { id = "registrationForm" })) {
%>
...
<button type="submit" onclick="return submitRegistration();">Register</button>
<%
    }
%>



<script type="text/javascript">
  function submitRegistration() {
    if ($("#registrationForm").valid()) {
      $.post('<%=Url.Action("{some action}")'...
    }
    // this is required to prevent the form from submitting
    return false;
  }
</script>

1 个解决方案

#1


2  

You can initiate jQuery validation on the button click event. Place the following inside your button-click event-handler:

您可以在按钮单击事件上启动jQuery验证。将以下内容放在按钮单击事件处理程序中:

if ($('form').valid())
   //take appropriate action for a valid form. e.g:
   $('form').post('<%=Url.Action("{some action}")%>')
else
   //take appropriate action for an invalid form

See the Validation plugin documentation for more information.

有关更多信息,请参阅Validation插件文档。

#1


2  

You can initiate jQuery validation on the button click event. Place the following inside your button-click event-handler:

您可以在按钮单击事件上启动jQuery验证。将以下内容放在按钮单击事件处理程序中:

if ($('form').valid())
   //take appropriate action for a valid form. e.g:
   $('form').post('<%=Url.Action("{some action}")%>')
else
   //take appropriate action for an invalid form

See the Validation plugin documentation for more information.

有关更多信息,请参阅Validation插件文档。