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

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

    You need to use a bit of reflection in order to access that attribute:

    var type = typeof(UserPromotion);
    var member = type.GetMember(Model.JobSeeker.Promotion.ToString());
    var attributes = member[0].GetCustomAttributes(typeof(DisplayAttribute), false);
    var name = ((DisplayAttribute)attributes[0]).Name;
    

    I recommend wrapping this method in a extension method or perform this in a view model.

提交回复
热议问题