一、模型数据注释
- ASP.NET MVC框架提供了数据验证的API,称为“模型数据注释”或“模型元数据”。
- 数据验证API位于
System.ComponentModel.DataAnnotations
名称空间。
数据验证API | 示例 | 说明 |
---|
Compare | [Compare(“name2”,ErrorMessage =“不一致”)] | 两个属性值必须一致 |
Range | [Range(1, 20, ErrorMessage = “数字范围1-20”)] | 数值范围 |
RegularExpression | [RegularExpression(@“正则表达式”+)+$", ErrorMessage =“请输入正确的邮箱地址”)] | 正则表达式校验 |
Required | [Required(ErrorMessage =“必填项”)] | 必填 |
StringLength | [StringLength(20,ErrorMessage =“字符范围10-20”,MinimumLength =10)] | 字符长度 |
二、demo
2.1 在model添加student类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MyMVCdemo01.Models
{
public class StudentModel
{
[Required(ErrorMessage ="必填项")]
[StringLength(20,ErrorMessage ="字符范围10-20",MinimumLength =10)]
public string id { get; set; }
[Compare("name2",ErrorMessage ="与name2不一致")]
public string name { get; set; }
public string name2 { get; set; }
[StringLength(20, ErrorMessage = "字符范围10-20", MinimumLength = 10)]
public string class_name { get; set; }
[RegularExpression(@"^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$", ErrorMessage ="请输入正确的邮箱地址")]
public string email { get; set; }
[Range(1, 20, ErrorMessage = "数字范围1-20")]
public int age { get; set; }
}
}
2.2 在Index视图添加表达,强类型引用student类型
@model MyMVCdemo01.Models.StudentModel
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
@using (Html.BeginForm("demo2", "Home", FormMethod.Post))
{
<table class="table table-bordered">
<tr>
<td>ID</td>
<td>
@Html.TextBoxFor(t => t.id)
</td>
<td>
@Html.ValidationMessageFor(t => t.id)
</td>
</tr>
<tr>
<td>name</td>
<td>@Html.TextBoxFor(t => t.name)</td>
<td>
@Html.ValidationMessageFor(t => t.name)
</td>
</tr>
<tr>
<td>name2</td>
<td> @Html.TextBoxFor(t => t.name2)</td>
<td>
@Html.ValidationMessageFor(t => t.name2)
</td>
</tr>
<tr>
<td>class_name</td>
<td> @Html.TextBoxFor(t => t.class_name)</td>
<td>
@Html.ValidationMessageFor(t => t.class_name)
</td>
</tr>
<tr>
<td>email</td>
<td> @Html.TextBoxFor(t => t.email)</td>
<td>
@Html.ValidationMessageFor(t => t.email)
</td>
</tr>
</table>
<input type="submit" class="btn btn-primary" value="提交"/>
}
</body>
</html>
2.3效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3470e18dc6c7fdec778300c7b9b9c5cf.png)