Efficiently displaying enum display names within your MVC Razor views requires accessing the attribute metadata. This can be elegantly handled using a custom extension method leveraging reflection.
The following extension method provides a clean solution:
<code class="language-csharp">public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) where TAttribute : Attribute { return enumValue.GetType() .GetMember(enumValue.ToString()) .First() .GetCustomAttribute<TAttribute>(); }</code>
This method uses reflection to examine the enum type and retrieve the first attribute of the specified type (TAttribute
) associated with the enum member matching the provided enum value.
Here's how to integrate this extension method into your Razor view:
<code class="language-csharp">@foreach (int aPromotion in Enum.GetValues(typeof(UserPromotion))) { var currentPromotion = (int)Model.JobSeeker.Promotion; if ((currentPromotion & aPromotion) == aPromotion) { <p>@((UserPromotion)aPromotion).GetAttribute<DisplayAttribute>().Name</p> } }</code>
This code iterates through the UserPromotion
enum values. For each value present in the Model.JobSeeker.Promotion
property (assuming it's a flags enum), it retrieves the DisplayAttribute
's Name
property using the extension method and displays it. This ensures that only the selected enum values are shown with their user-friendly display names.
The above is the detailed content of How to Retrieve Enum Display Names in MVC Razor Views?. For more information, please follow other related articles on the PHP Chinese website!