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
Release: 2025-01-27 09:16:10
Original
614 people have browsed it

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

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

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!

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