65.9K
CodeProject 正在变化。 阅读更多。
Home

如何在 ASP.NET MVC 2 中启用客户端验证

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2投票s)

2010年9月14日

CPOL

2分钟阅读

viewsIcon

34072

一篇解释如何在 ASP.NET MVC 2 中启用客户端验证的文章。

昨晚,我在一门ASP.NET课程中教授MVC框架。我向学生们展示了如何使用数据注解进行服务器端验证。我收到一个关于如何在MVC 2中启用客户端验证的问题,并决定写一篇关于它的文章。所以,开始吧…

MVC 服务器端验证

MVC 1中,我们没有开箱即用的客户端验证。为了实现验证,我们需要使用以下两种方法之一

  • 实现IDataErrorInfo接口。 这样,每个需要验证的模型实体都需要实现该接口。
  • 使用数据注解装饰每个模型实体进行验证。 这是我首选的方法,因为它更优雅,并且您不需要在模型实体内部保留验证实现。

这些方法是服务器端验证。 对于客户端验证,我们需要使用客户端库,例如jQuery Validator插件,并编写客户端验证代码。 在MVC 2中,这变得更容易实现。

在 MVC 2 中启用客户端验证

让我们看一个用数据注解装饰的实体

public class Course
{
  #region Properties

  public int CourseID { get; set; }

  [Required(ErrorMessage = "Course title is required")]
  public string Title { get; set; }

  [StringLength(5, ErrorMessage = "Course can have up to 5 days")]
  public string Days { get; set; }    
  public DateTime Time { get; set; }
  public string Location { get; set; }    
  [Range(1,4)]
  public int Credits { get; set; }

  #endregion
}

如您所见,course需要一个title,它的credit需要在14之间,并且Days属性的最大长度为 5 个字符。 在courses控制器中,我想进行验证,所以我像在MVC 1中那样连接服务器端验证

[HttpPost]
public ActionResult Create(Course course)
{
  try
  {
    if (ModelState.IsValid)
    {
      _courses.Add(course);
      return RedirectToAction("Index");
    }
    return View();
  }
  catch
  {
    return View();
  }
}

ModelState.IsValid属性将触发实体上的验证,我们将获得服务器端验证。 如果我们想要获得客户端验证,我们需要在视图中激活它。 在MVC 2中,我们在HtmlHelper类上还有另一个扩展方法可以帮助我们做到这一点。 该方法称为EnableClientValidation。 创建视图将如下所示

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<MvcApplication2.Models.Course>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Create
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Create</h2>
    <% Html.EnableClientValidation(); %>
    <% using (Html.BeginForm()) {%>
        <%: Html.ValidationSummary(true) %>

        <fieldset>
            <legend>Fields</legend>
            <div class="editor-label">
                <%: Html.LabelFor(model => model.CourseID) %>
            </div>
           <div class="editor-field">
                <%: Html.TextBoxFor(model => model.CourseID) %>
                <%: Html.ValidationMessageFor(model => model.CourseID) %>
            </div>
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Title) %>
           </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Title) %>
                <%: Html.ValidationMessageFor(model => model.Title) %>
            </div>
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Days) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Days) %>
                <%: Html.ValidationMessageFor(model => model.Days) %>
            </div>
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Time) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Time) %>
                <%: Html.ValidationMessageFor(model => model.Time) %>
            </div>
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Location) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Location) %>
                <%: Html.ValidationMessageFor(model => model.Location) %>
            </div>
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Credits) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Credits) %>
                <%: Html.ValidationMessageFor(model => model.Credits) %>
            </div>
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    <% } %>
    <div>
        <%: Html.ActionLink("Back to List", "Index") %>
    </div>
</asp:Content>

如果您现在运行该应用程序,您会看到即使您在视图中显式启用了客户端验证,它也不会运行。 原因在于您需要链接验证 JavaScript 文件才能启用验证。 以下是您需要链接的 JavaScript 文件(默认情况下存在于每个非空MVC 2应用程序中)

  • jquery-1.4.1.js
  • jquery.validate.js
  • MicrosoftAjax.js
  • MicrosoftMvcAjax.js
  • MicrosoftMvcValidation.js

链接它们的地方当然是母版页,以下是母版页的实现

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>  
    <script src="../../Scripts/jquery.validate.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>     
    <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <div id="header">
            <div id="title">
                <h1>My MVC Application</h1>
            </div>
            <div id="logindisplay">
                <% Html.RenderPartial("LogOnUserControl"); %>
            </div> 
            <div id="menucontainer">
                <ul id="menu">              
                    <li><%: Html.ActionLink("Home", "Index", "Home")%></li>
                    <li><%: Html.ActionLink("About", "About", "Home")%></li>
                </ul>
            </div>
        </div>

        <div id="main">
            <asp:ContentPlaceHolder ID="MainContent" runat="server" />
            <div id="footer">
            </div>
        </div>
    </div>
</body>
</html>

就是这样。 现在,您已在MVC 2 Web 应用程序中连接了客户端验证。

Validations in Action

摘要

MVC 2中,我们已经在框架内部实现了客户端验证。 我们所要做的就是链接一些 JavaScript 文件,并添加到相关的视图中以调用HtmlHelper类的EnableClientValidation方法。

© . All rights reserved.