第 6 部分:使用数据注释进行模型验证Part 6: Using Data Annotations for Model Validation

通过Jon Gallowayby Jon Galloway

MVC Music 商店是介绍,并说明如何使用 ASP.NET MVC 和 Visual Studio 进行 web 开发分步教程应用程序。The MVC Music Store is a tutorial application that introduces and explains step-by-step how to use ASP.NET MVC and Visual Studio for web development.

MVC Music 商店是该类销售音乐 album 联机,并实现基本的站点管理、 用户登录,和购物车功能存储区实现轻量的示例。The MVC Music Store is a lightweight sample store implementation which sells music albums online, and implements basic site administration, user sign-in, and shopping cart functionality.

本系列教程详细介绍所有构建 ASP.NET MVC Music 商店示例应用程序所采取的步骤。This tutorial series details all of the steps taken to build the ASP.NET MVC Music Store sample application. 第 6 部分介绍如何为模型验证中使用数据注释。Part 6 covers Using Data Annotations for Model Validation.

我们使用我们创建和编辑窗体具有一个主要问题: 未做任何验证。We have a major issue with our Create and Edit forms: they're not doing any validation. 我们可以执行某些操作,如在价格字段中,保留空白的必填的字段或键入字母,我们将看到的第一个错误来自数据库。We can do things like leave required fields blank or type letters in the Price field, and the first error we'll see is from the database.

我们可以轻松添加验证到我们的应用程序,这需要通过将数据批注添加到我们的模型类来实现。We can easily add validation to our application by adding Data Annotations to our model classes. 数据批注,我们可以描述应用于模型属性,我们想要的规则和 ASP.NET MVC 将负责强制执行它们并向我们的用户显示相应的消息。Data Annotations allow us to describe the rules we want applied to our model properties, and ASP.NET MVC will take care of enforcing them and displaying appropriate messages to our users.

向我们唱片集窗体中添加验证Adding Validation to our Album Forms

我们将使用以下数据注释属性:We'll use the following Data Annotation attributes:

  • 所需– 指示该属性是必填的字段Required – Indicates that the property is a required field
  • DisplayName – 定义要我们在窗体字段和验证消息使用的文本DisplayName – Defines the text we want used on form fields and validation messages
  • StringLength – 定义字符串字段的最大长度StringLength – Defines a maximum length for a string field
  • 范围– 为数字字段提供最大和最小值Range – Gives a maximum and minimum value for a numeric field
  • 将绑定– 列出要排除或包括当参数或窗体值绑定到模型属性的字段Bind – Lists fields to exclude or include when binding parameter or form values to model properties
  • ScaffoldColumn – 允许隐藏编辑器窗体中的字段ScaffoldColumn – Allows hiding fields from editor forms

注意:有关使用数据注释属性的模型验证的详细信息,请参阅上的 MSDN 文档https://go.microsoft.com/fwlink/?LinkId=159063Note: For more information on Model Validation using Data Annotation attributes, see the MSDN documentation athttps://go.microsoft.com/fwlink/?LinkId=159063

打开唱片集类并添加以下使用到顶部的语句。Open the Album class and add the following using statements to the top.

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

接下来,更新以添加显示和验证属性,如下所示的属性。Next, update the properties to add display and validation attributes as shown below.

namespace MvcMusicStore.Models
{
    [Bind(Exclude = "AlbumId")]
    public class Album
    {
        [ScaffoldColumn(false)]
        public int      AlbumId    { get; set; }
        [DisplayName("Genre")]
        public int      GenreId    { get; set; }
        [DisplayName("Artist")]
        public int      ArtistId   { get; set; }
        [Required(ErrorMessage = "An Album Title is required")]
        [StringLength(160)]
        public string   Title      { get; set; }
        [Range(0.01, 100.00,
            ErrorMessage = "Price must be between 0.01 and 100.00")]
        public decimal Price       { get; set; }
        [DisplayName("Album Art URL")]
        [StringLength(1024)]
        public string AlbumArtUrl { get; set; }
        public virtual Genre  Genre    { get; set; }
        public virtual Artist Artist   { get; set; }
    }
}

我们可以在那里,我们已更改为虚拟属性的流派和艺术家。While we're there, we've also changed the Genre and Artist to virtual properties. 这样,若要延迟加载它们根据需要的实体框架。This allows Entity Framework to lazy-load them as necessary.

public virtual Genre    Genre       { get; set; }
public virtual Artist   Artist      { get; set; }

后具有这些属性添加到我们唱片集的模型,我们创建和编辑屏幕立即开始验证字段,并使用显示名称,我们已选择 (例如唱片集画面 Url 而不是 AlbumArtUrl)。After having added these attributes to our Album model, our Create and Edit screen immediately begin validating fields and using the Display Names we've chosen (e.g. Album Art Url instead of AlbumArtUrl). 运行应用程序并浏览到 /StoreManager/Create。Run the application and browse to /StoreManager/Create.

接下来,我们将分一些验证规则。Next, we'll break some validation rules. 输入 0 的价格,然后将标题留空。Enter a price of 0 and leave the Title blank. 当我们单击创建按钮时,我们将看到显示验证错误消息显示哪些字段不符合验证规则我们已定义的窗体。When we click on the Create button, we will see the form displayed with validation error messages showing which fields did not meet the validation rules we have defined.

测试客户端验证Testing the Client-Side Validation

服务器端验证是从应用程序的角度看,非常重要,因为用户可以绕过客户端验证。Server-side validation is very important from an application perspective, because users can circumvent client-side validation. 但是,仅实现服务器端验证网页窗体表现出三个严重问题。However, webpage forms which only implement server-side validation exhibit three significant problems.

  1. 用户必须等待要发布,在服务器上,验证的窗体,并且要发送到其浏览器的响应。The user has to wait for the form to be posted, validated on the server, and for the response to be sent to their browser.
  2. 他们会校正字段,以便它现在通过验证规则时,用户不会获得即时反馈。The user doesn't get immediate feedback when they correct a field so that it now passes the validation rules.
  3. 我们都浪费服务器资源来执行验证逻辑,而不是利用用户的浏览器。We are wasting server resources to perform validation logic instead of leveraging the user's browser.

幸运的是,ASP.NET MVC 3 基架模板具有客户端验证内置的需要说明,否则任何额外工作。Fortunately, the ASP.NET MVC 3 scaffold templates have client-side validation built in, requiring no additional work whatsoever.

在标题字段中键入单个字母满足验证要求,以便验证消息将立即删除。Typing a single letter in the Title field satisfies the validation requirements, so the validation message is immediately removed.