Home >Backend Development >C++ >How to Retrieve Enum Display Names in MVC Razor Views?

How to Retrieve Enum Display Names in MVC Razor Views?

Barbara Streisand
Barbara StreisandOriginal
2025-01-27 09:16:10654browse

How to Retrieve Enum Display Names in MVC Razor Views?

Accessing Enum Display Names in MVC Razor Views

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.

Extension Method Approach

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.

Practical Implementation

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!

Statement:
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