Data annotations MVC3 Required attribute

余生长醉 提交于 2019-12-01 20:06:48

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!