Home > Backend Development > C++ > How to Display Enum Member Display Names in an MVC Razor View?

How to Display Enum Member Display Names in an MVC Razor View?

Mary-Kate Olsen
Release: 2025-01-27 09:31:08
Original
880 people have browsed it

How to Display Enum Member Display Names in an MVC Razor View?

Display the DisplayName property of enumeration members in an MVC Razor view

When working with enumerations, you often need to retrieve the display name property to display its user-friendly name. This Stack Overflow question addresses this need, especially in the context of MVC Razor views.

The task is to create a list of selected values ​​from the model's Promotion property, each value displayed along with its associated display name. The user-provided code snippet demonstrates retrieval of the enumeration value, but lacks a way to retrieve the display name property.

The solution lies in the EnumExtensions class provided in the accepted answer:

<code class="language-csharp">public static class EnumExtensions
{
    /// <summary>
    ///     一个通用的扩展方法,用于反射和检索应用于`Enum`的任何属性。
    /// </summary>
    public static TAttribute GetAttribute<TAttribute>(this Enum enumValue)
            where TAttribute : Attribute
    {
        return enumValue.GetType()
                        .GetMember(enumValue.ToString())
                        .First()
                        .GetCustomAttribute<TAttribute>();
    }
}</code>
Copy after login

Retrieving the display name property becomes very simple using this extension method:

<code class="language-csharp">var seasonDisplayName = Season.GetAttribute<DisplayAttribute>();
Console.WriteLine("现在是什么季节?");
Console.WriteLine(seasonDisplayName.Name);</code>
Copy after login

In your Razor view, you can modify the code to include the display name as follows:

<code class="language-csharp">@currentPromotion.GetAttribute<DisplayAttribute>().Name</code>
Copy after login

This approach improves user experience by allowing you to dynamically display the display names of enumeration members in the view.

The above is the detailed content of How to Display Enum Member Display Names in an MVC Razor View?. 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