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

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

    You could use Type.GetMember Method, then get the attribute info using reflection:

    // display attribute of "currentPromotion"
    
    var type = typeof(UserPromotion);
    var memberInfo = type.GetMember(currentPromotion.ToString());
    var attributes = memberInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
    var description = ((DisplayAttribute)attributes[0]).Name;
    

    There were a few similar posts here:

    Getting attributes of Enum's value

    How to make MVC3 DisplayFor show the value of an Enum's Display-Attribute?

提交回复
热议问题