MVC 4 Data Annotations “Display” Attribute

后端 未结 4 1274
夕颜
夕颜 2021-02-01 01:19

I am starting out with MVC 4 (Razor view engine). (I believe this may apply to MVC 3 and earlier as well.) I am wondering if there is any benefit to using the DisplayAttribute d

4条回答
  •  借酒劲吻你
    2021-02-01 01:54

    If two different views are sharing the same model (for instance, maybe one is for mobile output and one is regular), it could be nice to have the string reside in a single place: as metadata on the ViewModel.

    Additionally, if you had an inherited version of the model that necessitated a different display, it could be useful. For instance:

    public class BaseViewModel
    {
        [Display(Name = "Basic Name")]
        public virtual string Name { get; set; }
    }
    
    public class OtherViewModel : BaseViewModel
    {
        [Display(Name = "Customized Inherited Name")]
        public override string Name { get; set; }
    }
    

    I'll admit that that example is pretty contrived...

    Those are the best arguments in favor of using the attribute that I can come up with. My personal opinion is that, for the most part, that sort of thing is best left to the markup.

提交回复
热议问题