Visual
Data Annotations
Tag Helper 结合 Data Annotations 可以生成不同属性的标签及验证规则。
Data Annotations 示例:
public class StudentCreateViewModel
{
[Display(Name = "名")]
[Required]
public string FirstName { get; set; }
[Display(Name = "姓"), Required, MaxLength(10)]
public string LastName { get; set; }
[Display(Name = "出生日期")]
public DateTime BirthDate { get; set; }
[Display(Name = "性别")]
public Gender Gender { get; set; }
}
View 中显式验证信息:
@using Tutorial.Web.Model
@model Tutorial.Web.ViewModels.StudentCreateViewModel
<h1>创建学生</h1>
<form method="post">
<div>
<label asp-for="FirstName"></label>
<input asp-for="FirstName" />
<span asp-validation-for="FirstName"></span>
</div>
<div>
<label asp-for="LastName"></label>
<input asp-for="LastName" />
<span asp-validation-for="LastName"></span>
</div>
<div>
<label asp-for="BirthDate"></label>
<input asp-for="BirthDate" type="date" />
<span asp-validation-for="BirthDate"></span>
</div>
<div>
<label asp-for="Gender"></label>
<select asp-for="Gender" asp-items="Html.GetEnumSelectList<Gender>()"></select>
<span asp-validation-for="Gender"></span>
</div>
<div asp-validation-summary="ModelOnly"></div>
<button type="submit" name="save">保存</button>
</form>
Controller 中读取验证信息:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(StudentCreateViewModel student)
{
if (ModelState.IsValid)
{
var newStudent = new Student
{
FirstName = student.FirstName,
LastName = student.LastName,
BirthDate = student.BirthDate,
Gender = student.Gender
};
var newModel = _repository.Add(newStudent);
return RedirectToAction(nameof(Detail), new { id = newModel.Id });
}
ModelState.AddModelError(string.Empty, "Model Level Error!");
return View();
}