Development data annotation based on Model layer in MVC5

  • 2021-10-16 01:21:53
  • OfStack

ASP. NET MVC5 Model layer development, using data annotations have three functions:

Data mapping (mapping classes of Model layer to corresponding tables with EntityFramework)

Data validation (validating data on the server and client sides)

Data display (the corresponding data is displayed in View layer)

Namespaces related to data annotations are as follows:

System.ComponentModel.DataAnnotations

System.ComponentModel.DataAnnotations.Schema

System.Web.Mvc

System.Web.Security

The DataAnnotations namespace contains major data annotations, the Schema namespace contains data annotations for data mapping, the Mvc namespace contains data annotations for character, array, numeric length and attribute comparison, and the MemberShipPassword annotation feature is included in the Security namespace.

Data annotations related to data mapping and validation:

[Required] 必填字段
[MaxLength] 指定属性中允许的数组或字符串数据的最大长度
[MinLength] 指定属性中允许的数组或字符串数据的最小长度
[StringLength] 指定最小和最大字符长度
[Range] 指定数值范围

Data annotations related to data validation:

[Remote] 使用 jQuery 验证插件远程验证程序的特性
[FileExtension] 验证文件扩展名
[Compare] 比较两个属性的值
[RegularExpression] 使用正则表达式验证
[CustomValidation] 自定义验证方法
[DataType] 指定要与数据字段关联的附加类型的名称
[EmailAddress] 电子邮件地址(相当于[DataType(DataType.Email)])
[Phone] 电话(同上)
[CreditCard] 信用卡号码(同上)
[Url] 验证URL(同上)
[MemberShipPassword] 验证密码字段是否满足成员资格提供程序的当前密码要求

Data annotations related to data mapping:

[Key] Primary key field [Column] Database column attribute mapping [NotMapped] Do not create corresponding fields [Table] Specify the database table to which the class will map [ForeignKey] Represents an attribute used as a foreign key in a relationship [DatabaseGenerated] Specifies how the database generates property values (EF does not track property changes)

Data display related data annotations:

[DisplayName] 指定本地化的字符串(习惯用语类)
[Display] 指定本地化的字符串(习惯用语属性)
[DisplayFormat] 设置数据字段的格式
[ReadOnly] 指定该特性所绑定到的属性是只读属性还是读/写属性
[EditAble] 指示数据字段是否可编辑
[HiddenInput] 指示是否应将属性值或字段值呈现为隐藏的 input 元素
[ScaffoldColumn] 指定类或数据列是否使用基架
[UIHint] 指定动态数据用来显示数据字段的模板

Others

[DisplayColumn] 将所引用的表中显示的列指定为外键列
[Description]

可视化设计器在引用组件成员时可以显示指定的说明

(命名空间:System.ComponentModel.DescriptionAttribute

1. Data annotations related to data validation inherit the ValidationAttribute class, and all have an ErrorMessage attribute to display error prompts.

For example, [Required (ErrorMessage= "This item cannot be empty")].

2. NULL type and DateTime type in data mapping are not allowed to be NULL by default in database. If you need to set it to NULL, you can use nullable type (use Int? Or DateTime?) .


Related articles: