gpt4 book ai didi

c# - 使用 System.ComponentModel.DataAnnotations 进行模型绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 11:59:38 25 4
gpt4 key购买 nike

我正在使用 System.ComponentModel.DataAnnotations 进行模型绑定(bind)并验证我的 ASP.NET MVC 应用程序。

我有一个这样的 C# 模型类

public class Employee
{
public Int64 EmployeeId { get; set; }

[Required]
public string FullName { get; set; }

[Required]
public string Username { get; set; }

public string Password { get; set; }

[Compare("Password")]
public string ConfirmPassword { get; set; }
}

当我通过 AJAX 提交表单以插入记录时,值被正确设置为 Employee 对象。

但是 ModelState.IsValid 语句总是错误的,它说 The EmployeeId field is required

因为EmployeeId是数据库中的标识列,所以我没有在 Controller 中设置它。

我该如何解决这个问题?

当我更新记录时,我需要根据需要制作EmployeeId。我该如何处理呢?

最佳答案

我认为最简单/最干净的是使 EmployeeId 可为空:

public class Employee
{
public Int64? EmployeeId { get; set; }

// ...
}

关于c# - 使用 System.ComponentModel.DataAnnotations 进行模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57621040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com