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

后端 未结 20 2726
孤街浪徒
孤街浪徒 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:40

    Using MVC5 you could use:

    public enum UserPromotion
    {
       None = 0x0,
    
       [Display(Name = "Send Job Offers By Mail")]
       SendJobOffersByMail = 0x1,
    
       [Display(Name = "Send Job Offers By Sms")]
       SendJobOffersBySms = 0x2,
    
       [Display(Name = "Send Other Stuff By Sms")]
       SendPromotionalBySms = 0x4,
    
       [Display(Name = "Send Other Stuff By Mail")]
       SendPromotionalByMail = 0x8
    }
    

    then if you want to create a dropdown selector you can use:

    @Html.EnumDropdownListFor(expression: model => model.PromotionSelector, optionLabel: "Select") 
    

提交回复
热议问题