Skip to main content
 首页 » 编程设计

c#之MVC 阻止更新某些字段

2024年02月06日13jackei

我有一个使用存储库模式和 Entity Framework 6 的 ASP.NET MVC 4 应用程序。

当我访问 User/Details/5 页面并更新用户详细信息时,出现以下错误 -

The property 'Password' cannot be set to a null value.

在我看来,除了密码之外,我还有所有这些字段,因为在此 View 中我不需要它。我如何(基本上)告诉 MVC 不要更新此 View 中的密码?

这是我的用户模型

public class UserModel : IUserModel 
{ 
    public int Id{ get; set; } 
 
    [DisplayName("Employee Number")] 
    public int EmployeeNumber { get; set; } 
 
    [DisplayName("First Name")] 
    public string Firstname { get; set; } 
 
    [DisplayName("Last Name")] 
    public string Surname { get; set; } 
 
    public string Email { get; set; } 
 
    [DisplayName("User Type")] 
    public UserType UserType { get; set; } 
 
    [DisplayName("Login")] 
    public UserStatus UserStatus { get; set; } 
 
    [DisplayName("Login Status")] 
    public bool LoginStatus { get; set; } 
 
    public string Password { get; set; } 
 
    [ReadOnly(true)] 
    public DateTime DateCreated { get; set; } 
 
    [ReadOnly(true)] 
    public int CreatedBy { get; set; } 
 
    [ReadOnly(true)] 
    public DateTime LastUpdated { get; set; } 
 
    [ReadOnly(true)] 
    public int LastUpdateBy { get; set; } 
 
    [DisplayName("Full Name")] 
    public string SurnameFirstName 
    { 
        get { return Surname + ", " + Firstname; } 
    } 
 
    [NotMapped] 
    public State State { get; set; } 
} 

这是我的 Controller -

[HttpPost] 
    public ActionResult Details(UserModel model) 
    { 
        if (ModelState.IsValid) 
        { 
 
            _userService.Update(model); 
 
            return RedirectToAction("Index"); 
        } 
 
        return View(model); 
    } 

还有我的 _userService.Update 方法

public void Update(UserModel entity) 
    { 
        User u = _userRepository.FindById(entity.Id); 
 
        AutoMapper.Mapper.CreateMap<UserModel, User>(); 
 
        _userRepository.Update(AutoMapper.Mapper.Map(entity, u)); 
    } 

请您参考如下方法:

你的关键句是这样的:

在我看来,除了密码之外,我还有所有这些字段,因为在此 View 中我不需要它。

您应该定义 ViewModels 而不是使用模型(我知道有很多示例可以像您一样这样做,但最佳做法是使用 View 模型)。

ViewModel 基本上是一个为您的 View 建模的类,因此它只包含您需要的属性。获得此信息后,您可以按照@krillgar 在评论中所说的那样更新您的模型:从数据库中拉出用户并仅更新您要更新的字段。