MVC 4 Data Annotations “Display” Attribute

后端 未结 4 1272
夕颜
夕颜 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:38

    In addition to the other answers, there is a big benefit to using the DisplayAttribute when you want to localize the fields. You can lookup the name in a localization database using the DisplayAttribute and it will use whatever translation you wish.

    Also, you can let MVC generate the templates for you by using Html.EditorForModel() and it will generate the correct label for you.

    Ultimately, it's up to you. But the MVC is very "Model-centric", which is why data attributes are applied to models, so that metadata exists in a single place. It's not like it's a huge amount of extra typing you have to do.

    0 讨论(0)
  • 2021-02-01 01:45

    One of the benefits is you can use it in multiple views and have a consistent label text. It is also used by asp.net MVC scaffolding to generate the labels text and makes it easier to generate meaningful text

    [Display(Name = "Wild and Crazy")]
    public string WildAndCrazyProperty { get; set; }
    

    "Wild and Crazy" shows up consistently wherever you use the property in your application.

    Sometimes this is not flexible as you might want to change the text in some view. In that case, you will have to use custom markup like in your second example

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

    0 讨论(0)
  • 2021-02-01 01:58

    Also internationalization.

    I fooled around with this some a while back. Did this in my model:

    [Display(Name = "XXX", ResourceType = typeof(Labels))]
    

    I had a separate class library for all the resources, so I had Labels.resx, Labels.culture.resx, etc.

    In there I had key = XXX, value = "meaningful string in that culture."

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