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

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 命名空间中提供的属性来指定验证规则。例如:

复制代码
cs 复制代码
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 属性来检查模型是否通过验证。

复制代码
cs 复制代码
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 辅助方法来显示验证错误消息。

复制代码
cs 复制代码
@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 进行模型绑定和验证。这些属性可以帮助你轻松地定义和执行数据验证规则,从而提高应用程序的数据完整性和安全性。

相关推荐
千寻girling1 小时前
《 Git 详细教程 》
前端·后端·面试
0xDevNull2 小时前
Linux 中 Nginx 代理 Redis 的详细教程
redis·后端
GetcharZp3 小时前
告别 Nginx 手动配置!这款 Go 语言开发的云原生网关,才是容器化时代的真香神器!
后端
RuoyiOffice3 小时前
SpringBoot+Vue3 企业考勤如何处理法定假期?节假日方案、调休补班与工作日判断链路拆解
spring boot·后端·vue·anti-design-vue·ruoyioffice·假期·人力
Vane13 小时前
从零开发一个AI插件,经历了什么?
人工智能·后端
952364 小时前
SpringBoot统一功能处理
java·spring boot·后端
rleS IONS4 小时前
SpringBoot中自定义Starter
java·spring boot·后端
DevilSeagull4 小时前
MySQL(2) 客户端工具和建库
开发语言·数据库·后端·mysql·服务
TeDi TIVE5 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
雨辰AI5 小时前
SpringBoot3 + 人大金仓 V9 微服务监控实战|Prometheus+Grafana+SkyWalking 全链路监控
数据库·后端·微服务·grafana·prometheus·skywalking