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

相关推荐
ai小鬼头23 分钟前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
Touper.29 分钟前
SpringBoot -- 自动配置原理
java·spring boot·后端
一只叫煤球的猫1 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
一只鹿鹿鹿1 小时前
信息化项目验收,软件工程评审和检查表单
大数据·人工智能·后端·智慧城市·软件工程
专注VB编程开发20年2 小时前
开机自动后台运行,在Windows服务中托管ASP.NET Core
windows·后端·asp.net
程序员岳焱2 小时前
Java 与 MySQL 性能优化:MySQL全文检索查询优化实践
后端·mysql·性能优化
一只叫煤球的猫2 小时前
手撕@Transactional!别再问事务为什么失效了!Spring-tx源码全面解析!
后端·spring·面试
旷世奇才李先生2 小时前
Ruby 安装使用教程
开发语言·后端·ruby
沃夫上校5 小时前
Feign调Post接口异常:Incomplete output stream
java·后端·微服务
LeeGe5 小时前
SpringAOP中@within和@annotation以及 @within和@target的区别
后端