How to get the Display Name Attribute of an Enum member via MVC razor code?

后端 未结 20 2832
孤街浪徒
孤街浪徒 2020-11-22 09:30

I\'ve got a property in my model called \"Promotion\" that its type is a flag enum called \"UserPromotion\". Members of my enum have display attributes set as follows:

20条回答
  •  忘掉有多难
    2020-11-22 09:48

    If you are using MVC 5.1 or upper there is simplier and clearer way: just use data annotation (from System.ComponentModel.DataAnnotations namespace) like below:

    public enum Color
    {
        [Display(Name = "Dark red")]
        DarkRed,
        [Display(Name = "Very dark red")]
        VeryDarkRed,
        [Display(Name = "Red or just black?")]
        ReallyDarkRed
    }
    

    And in view, just put it into proper html helper:

    @Html.EnumDropDownListFor(model => model.Color)
    

提交回复
热议问题