ASP.NET Core 入门教学二十三 模型绑定和验证

发布于:2024-09-18 ⋅ 阅读:(15) ⋅ 点赞:(0)

System.ComponentModel.DataAnnotations 命名空间提供了用于在 .NET 应用程序中进行数据验证和绑定的属性。在 ASP.NET Core 中,这些属性可以与模型绑定和模型验证一起使用,以确保用户输入的数据有效且符合预期的格式。

以下是如何使用 System.ComponentModel.DataAnnotations 进行模型绑定和验证的步骤:

1. 添加必要的 NuGet 包

确保你的项目中已经安装了 Microsoft.AspNetCore.Mvc.DataAnnotations 包。如果没有,可以通过 NuGet 包管理器或使用以下命令安装:


dotnet add package Microsoft.AspNetCore.Mvc.DataAnnotations

2. 在模型类中使用数据注解

在你的模型类中,使用 System.ComponentModel.DataAnnotations 命名空间中提供的属性来指定验证规则。例如:


using System.ComponentModel.DataAnnotations;

public class User
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Name is required.")]
    [StringLength(50, MinimumLength = 3, ErrorMessage = "Name must be between 3 and 50 characters.")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Email is required.")]
    [EmailAddress(ErrorMessage = "Invalid email address.")]
    public string Email { get; set; }
}

3. 在控制器中处理模型绑定和验证

在控制器中,使用 [HttpPost] 或 [HttpPut] 等方法来处理表单提交或其他数据输入。使用 ModelState.IsValid 属性来检查模型是否通过验证。


using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

public class UserController : Controller
{
    [HttpGet]
    public IActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Create([Bind("Name,Email")] User user)
    {
        if (ModelState.IsValid)
        {
            // 保存用户到数据库或其他操作
            return RedirectToAction("Index");
        }

        // 如果模型无效,重新显示表单,并显示错误消息
        return View(user);
    }
}

4. 在视图中显示验证错误消息

在视图中,使用 Html.ValidationMessageFor 辅助方法来显示验证错误消息。


@model User

<form asp-action="Create">
    <div>
        <label asp-for="Name"></label>
        <input asp-for="Name" />
        <span asp-validation-for="Name"></span>
    </div>
    <div>
        <label asp-for="Email"></label>
        <input asp-for="Email" />
        <span asp-validation-for="Email"></span>
    </div>
    <button type="submit">Submit</button>
</form>

5. 配置数据注解验证器

在 Startup.cs 文件中,确保已经配置了数据注解验证器。


public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews()
            .AddDataAnnotations(); // 添加数据注解支持
}

通过以上步骤,你可以在 ASP.NET Core 应用程序中使用 System.ComponentModel.DataAnnotations 进行模型绑定和验证。这些属性可以帮助你轻松地定义和执行数据验证规则,从而提高应用程序的数据完整性和安全性。