Data annotations MVC3 Required attribute

前端 未结 2 1927
暖寄归人
暖寄归人 2021-01-19 22:07

I have the Model (User) below, I use it to add new users and to update existing users. When I\'m adding a new user it\'s required to enter the user name and the password, a

2条回答
  •  春和景丽
    2021-01-19 22:50

    You should use view models.

    Your data annotations would then belong on the view model being passed to the view

    public class CreateViewModel
    {
      public int ID { get; set; }
    
      [Display(Name = "Nome do Usuário")]
      [Required(ErrorMessage = "Digite o Nome do Usuário.")]
      public string name { get; set; }
    
      [Display(Name = "Senha")]
      [Required(ErrorMessage = "Digite a Senha.")]
      public string password { get; set; }
    }
    

    and for edit

     public class EditViewModel
        {
          public int ID { get; set; }
    
          [Display(Name = "Nome do Usuário")]
          [Required(ErrorMessage = "Digite o Nome do Usuário.")]
          public string name { get; set; }
    
          //perhaps you don't need the password at all in the edit view
        }
    

    Pass these classes to your view(s), not your domain model(User), then, in the controller, map the view model properties back to the model before persisting to your data source.

提交回复
热议问题