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

相关推荐
一 乐6 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
码事漫谈7 小时前
Protocol Buffers 编码原理深度解析
后端
码事漫谈7 小时前
gRPC源码剖析:高性能RPC的实现原理与工程实践
后端
踏浪无痕8 小时前
AI 时代架构师如何有效成长?
人工智能·后端·架构
程序员小假9 小时前
我们来说一下无锁队列 Disruptor 的原理
java·后端
武子康10 小时前
大数据-209 深度理解逻辑回归(Logistic Regression)与梯度下降优化算法
大数据·后端·机器学习
maozexijr10 小时前
Rabbit MQ中@Exchange(durable = “true“) 和 @Queue(durable = “true“) 有什么区别
开发语言·后端·ruby
源码获取_wx:Fegn089510 小时前
基于 vue智慧养老院系统
开发语言·前端·javascript·vue.js·spring boot·后端·课程设计
独断万古他化11 小时前
【Spring 核心: IoC&DI】从原理到注解使用、注入方式全攻略
java·后端·spring·java-ee
毕设源码_郑学姐11 小时前
计算机毕业设计springboot基于HTML5的酒店预订管理系统 基于Spring Boot框架的HTML5酒店预订管理平台设计与实现 HTML5与Spring Boot技术驱动的酒店预订管理系统开
spring boot·后端·课程设计