用于ajax表单的ASP.NET MVC 2服务器端验证

时间:2010-07-20 13:57:53

标签: ajax validation asp.net-mvc-2 webforms server-side

我遇到了以下问题。我正在为网站开发一个表单,这个表单应该有验证。我想使用本机ASP.NET MVC 2验证功能,但对它很顽固。我有一个通过$ .get加载的表单,并使用jQuery UI模式对话框显示。我找到的所有示例都解释了如何使用简单形式使用MVC验证并避免使用Ajax表单。

我可以为此表单启用客户端验证,但我需要正确处理服务器端验证。如何处理ajax表单的服务器端验证模型错误?

1 个答案:

答案 0 :(得分:1)

将对象传递回控制器时,必须将代码包装在If ModelState.IsValid

以下是我编辑用户的简化版本。第一个“EDIT”将User对象发送给View。第二个“编辑”处理视图中的帖子。

Function Edit() As ActionResult
    ''# do stuff to populate your User
    Return View(User)
End Function

<AcceptVerbs(HttpVerbs.Post)> _
Function Edit(ByVal user as User)
    If ModelState.IsValid Then
        ''# do your valid stuff
    Else
        ''# The posted form was not valid, send the user back
        Return View(user)
    End If
End Function

C#

中的情况与此相同
public ActionResult Edit()
{
    // do stuff to populate your User
    return View(User);
}

[AcceptVerbs(HttpVerbs.Post)]
public object Edit(User user)
{
    if (ModelState.IsValid) {
            // do your valid stuff
    } else {
        //'# The posted form was not valid, send the user back
        return View(user);
    }
}

编辑:

在您的视图中,如果您想添加AJAX验证,只需添加以下内容。

    <% 
        Html.EnableClientValidation() ''# This is where all the magic happens.  It will build your clientside validation for you out of your MetaData.
        Using Html.BeginForm("Edit", "Users")
    %>

      <!-- all your markup crap -->
            <tr>
                <td>
                    <%: Html.LabelFor(Function(model) model.UserName)%></td>
                <td>
                    <%: Html.TextBoxFor(Function(model) model.UserName) %>
                    <%: Html.ValidationMessage("UserName", "*")%><br />
                </td>
            </tr>

      <!-- somewhere you'll want to add a Validation Summary of all your errors -->
      <%= Html.ValidationSummary("Oops!, please correct the errors...") %>


      <% End Using%>
      <!-- bottom of the page -->

          <script src="../../Assets/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
          <script src="../../Assets/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
          <script src="../../Assets/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>

编辑:

以下是使用Ajax.BeginForm进行渲染的一些信息 http://singulartechnologies.com/asp-net-mvc-ajax-beginform-sample-code
http://msdn.microsoft.com/en-us/library/dd381533.aspx
http://weblogs.asp.net/mikebosch/archive/2008/02/15/asp-net-mvc-submitting-ajax-form-with-jquery.aspx