09 Model 验证.mp4 (47.5MB)

Data Annotations

Tag Helper 结合 Data Annotations 可以生成不同属性的标签及验证规则。

Data Annotations 示例:

  1. public class StudentCreateViewModel
  2. {
  3. [Display(Name = "名")]
  4. [Required]
  5. public string FirstName { get; set; }
  6. [Display(Name = "姓"), Required, MaxLength(10)]
  7. public string LastName { get; set; }
  8. [Display(Name = "出生日期")]
  9. public DateTime BirthDate { get; set; }
  10. [Display(Name = "性别")]
  11. public Gender Gender { get; set; }
  12. }

View 中显式验证信息:

  1. @using Tutorial.Web.Model
  2. @model Tutorial.Web.ViewModels.StudentCreateViewModel
  3. <h1>创建学生</h1>
  4. <form method="post">
  5. <div>
  6. <label asp-for="FirstName"></label>
  7. <input asp-for="FirstName" />
  8. <span asp-validation-for="FirstName"></span>
  9. </div>
  10. <div>
  11. <label asp-for="LastName"></label>
  12. <input asp-for="LastName" />
  13. <span asp-validation-for="LastName"></span>
  14. </div>
  15. <div>
  16. <label asp-for="BirthDate"></label>
  17. <input asp-for="BirthDate" type="date" />
  18. <span asp-validation-for="BirthDate"></span>
  19. </div>
  20. <div>
  21. <label asp-for="Gender"></label>
  22. <select asp-for="Gender" asp-items="Html.GetEnumSelectList<Gender>()"></select>
  23. <span asp-validation-for="Gender"></span>
  24. </div>
  25. <div asp-validation-summary="ModelOnly"></div>
  26. <button type="submit" name="save">保存</button>
  27. </form>

image.png

Controller 中读取验证信息:

  1. [HttpPost]
  2. [ValidateAntiForgeryToken]
  3. public IActionResult Create(StudentCreateViewModel student)
  4. {
  5. if (ModelState.IsValid)
  6. {
  7. var newStudent = new Student
  8. {
  9. FirstName = student.FirstName,
  10. LastName = student.LastName,
  11. BirthDate = student.BirthDate,
  12. Gender = student.Gender
  13. };
  14. var newModel = _repository.Add(newStudent);
  15. return RedirectToAction(nameof(Detail), new { id = newModel.Id });
  16. }
  17. ModelState.AddModelError(string.Empty, "Model Level Error!");
  18. return View();
  19. }

源码

Tutorial.zip