ASP.NET Core应用程序12:使用模型验证

  模型验证是确保请求中提供的数据是有效的。
  本章描述 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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值