Data annotations MVC3 Required attribute

前端 未结 2 1913
暖寄归人
暖寄归人 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:49

    I normally specify in my BaseViewModel which elements to hide, then use jQuery to hide them. It can mess with your layout though, if you use more 'fancy' layouts than my usual top to bottom column-based layouts. Hide form-group for each element to be hidden, and the elements below it just shift upwards.

    My main line of work is LOB intranet apps, so I skip all the fancy most of the time.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题