When working with enumerations, you often need to retrieve the display name property to display its user-friendly name. This Stack Overflow question addresses this need, especially in the context of MVC Razor views.
The task is to create a list of selected values from the model's Promotion property, each value displayed along with its associated display name. The user-provided code snippet demonstrates retrieval of the enumeration value, but lacks a way to retrieve the display name property.
The solution lies in the EnumExtensions class provided in the accepted answer:
<code class="language-csharp">public static class EnumExtensions { /// <summary> /// 一个通用的扩展方法,用于反射和检索应用于`Enum`的任何属性。 /// </summary> public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) where TAttribute : Attribute { return enumValue.GetType() .GetMember(enumValue.ToString()) .First() .GetCustomAttribute<TAttribute>(); } }</code>
Retrieving the display name property becomes very simple using this extension method:
<code class="language-csharp">var seasonDisplayName = Season.GetAttribute<DisplayAttribute>(); Console.WriteLine("现在是什么季节?"); Console.WriteLine(seasonDisplayName.Name);</code>
In your Razor view, you can modify the code to include the display name as follows:
<code class="language-csharp">@currentPromotion.GetAttribute<DisplayAttribute>().Name</code>
This approach improves user experience by allowing you to dynamically display the display names of enumeration members in the view.
The above is the detailed content of How to Display Enum Member Display Names in an MVC Razor View?. For more information, please follow other related articles on the PHP Chinese website!