Displaying Enum Member Names in ASP.NET MVC Razor Views
When working with enums enhanced with display attributes in ASP.NET MVC Razor views, efficiently accessing these display names is crucial for creating user-friendly interfaces. This article presents a solution to achieve this.
The challenge lies in retrieving the display names of enum members based on their flag values. A common approach involves using reflection. The following extension method, GetAttribute()
, facilitates this:
<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 dynamically retrieves any attribute associated with an enum member.
Applying this to your Razor view, the improved code would look like this:
<code class="language-csharp">@foreach (var aPromotion in Enum.GetValues(typeof(UserPromotion))) { var currentPromotion = (int)Model.JobSeeker.Promotion; if ((currentPromotion & aPromotion) == aPromotion) { @aPromotion.GetAttribute<DisplayAttribute>().Name } }</code>
This revised Razor code leverages the GetAttribute()
method to obtain the DisplayAttribute
for each enum member in the loop. The Name
property of the retrieved attribute then provides the desired display name. This approach ensures that user-friendly names are displayed instead of the underlying enum values.
The above is the detailed content of How to Get Display Names of Enum Members in ASP.NET MVC Razor Views?. For more information, please follow other related articles on the PHP Chinese website!