模型验证是确保请求中提供的数据是有效的。
本章描述 ASP.NET Core 数据验证功能。解释了如何显式地执行验证,如何使用属性来播述验证约束,以及如何验证单个属性和整个对象。演示了如何向用户显示验证消息,以及如何通过客户端和远程验证改进用户的验证体验。
1 准备工作
继续使用上一章项目。
修改 Views/Form 文件夹的 Form.cshtml。
@model Product
@{
Layout = "_SimpleLayout";
}
<h5 class="bg-primary text-white text-center p-2">HTML Form</h5>
<form asp-action="submitform" method="post" id="htmlform">
<div class="form-group">
<label asp-for="Name"></label>
<input class="form-control" asp-for="Name" />
</div>
<div class="form-group">
<label asp-for="Price"></label>
<input class="form-control" asp-for="Price" />
</div>
<div class="form-group">
<label>CategoryId</label>
<input class="form-control" asp-for="CategoryId" />
</div>
<div class="form-group">
<label>SupplierId</label>
<input class="form-control" asp-for="SupplierId" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
替换 Controllers 文件夹中 FormController.cs 。
public class FormController : Controller
{
private DataContext context;
public FormController(DataContext dbContext)
{
context = dbContext;
}
public async Task<IActionResult> Index(long? id)
{
var result = await context.Products
.FirstOrDefaultAsync(p => id == null || p.ProductId == id);
return View("Form", result);
}
[HttpPost]
public IActionResult SubmitForm(Product product)
{
TempData["name"] = product.Name;
TempData["price"] = product.Price.ToString();
TempData["categoryId"] = product.CategoryId.ToString();
TempData["supplierId"] = product.SupplierId.ToString();
return RedirectToAction(nameof(Results));
}
public IActionResult Results()
{
return View(TempData);
}
}
2 理解对模型验证的需要
验证数据最直接的方法是在操作或处理程序方法中进行验证。
[HttpPost]
public IActionResult SubmitForm(Product product)
{
if (string.IsNullOrEmpty(product.Name))
{
ModelState.AddModelError(nameof(Product.Name), "Enter a name");
}
if (ModelState.GetValidationState(nameof(Product.Price))
== ModelValidationState.Valid && product.Price < 1)
{
ModelState.AddModelError(nameof(Product.Price),
"Enter a positive price");
}
if (!context.