Home > Backend Development > C++ > How to Get Display Names of Enum Members in ASP.NET MVC Razor Views?

How to Get Display Names of Enum Members in ASP.NET MVC Razor Views?

Mary-Kate Olsen
Release: 2025-01-27 09:11:13
Original
394 people have browsed it

How to Get Display Names of Enum Members in ASP.NET MVC Razor Views?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template