ASP.Net Core -- 模型验证
模型验证就是我们可以给模型类中的属性添加一些规则,然后判别用户输入的信息是否符合。比如,有些属性必填,有的是密码不可见,然后当用户提交Post请求后,框架就会进行验证,如果不通过,可以把错误信息返回给用户!
比如有这样一个模型类:
public class StudentCreateViewModel { [Display(Name = "姓"),Required] [DataType(DataType.Password)] public string FirstName { get; set; } [Display(Name = "名"),Required,MaxLength(10)] public string LastName { get; set; } [Display(Name = "出生日期"), Required] public DateTime BirthDate { get; set; } [Display(Name = "性别")] public Gender Gender { get; set; } }
我们给姓设置了必填,并且将类型设置为密码不可见,等等......然后在控制器中就可以判断验证是否通过:
[HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(StudentCreateViewModel student) { if (ModelState.IsValid) { var list = new Student { FirstName = student.FirstName, LastName = student.LastName, BirthDate = student.BirthDate, Gender = student.Gender }; var newModel = _repository.Add(list); return RedirectToAction(nameof(Detail), new { id = newModel.Id }); } return View(); }
通过就跳转到页面将添加的信息显示,否则就打印错误信息,如下:
<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> <input type="submit" value="save" /> </form>
同时,我们还可以将属性级的错误信息一次性打印出来,可以在form表单下使用:
<div asp-validation-summary="All"></div>
这是属性级错误,也可输出Model级的错误,比如在后端添加:
ModelState.AddModelError(string.Empty, "Model level error");
然后使用:
<div asp-validation-summary="ModelOnly"></div>
来显示model级的错误信息