in the MVC Razor code
In the ASP.NET MVC Razor view, the display name of accessing enumeration members is essential to describe a friendly description to users. This article discusses how to retrieve these display names in the context of the MVC Razor code.Problem description
Given a lift member who modifies [Display] attributes, challenges to extract these display names in the Razor code. The author intends to fill a list with the selection value of the promotion enumerated, and each value shows the corresponding display name.
Solution
In order to solve this problem, we use an extension method to make the province in the province and search for specific attributes applied to its members. The following is the code of the expansion method:
This method is used as a general method to retrieve any attributes applied to enumeration members. In our example, we want to retrieve the [Display] property to obtain its name attribute.
<code class="language-csharp">public static class Extensions { public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) where TAttribute : Attribute { return enumValue.GetType() .GetMember(enumValue.ToString()) .First() .GetCustomAttribute<TAttribute>(); } }</code>
Using the expansion method, we can now modify the Razor code as follows:
This code retrieves the [Display] property of the current promotion, and access its name property to display the corresponding display name in the list item. Note that the modified code usesfor type conversion, which is more secure and reliable to obtain attributes.
<code class="language-csharp">@foreach (int aPromotion in Enum.GetValues(typeof(UserPromotion))) { var currentPromotion = (int)Model.JobSeeker.Promotion; if ((currentPromotion & aPromotion) == aPromotion) { var displayName = ((UserPromotion)aPromotion).GetAttribute<DisplayAttribute>().Name; <li>@displayName</li> } }</code>
((UserPromotion)aPromotion)
Output:
<code class="language-csharp">public class Foo { public Season Season { get; set; } public void DisplayName() { var seasonDisplayName = Season.GetAttribute<DisplayAttribute>(); Console.WriteLine("Which season is it?"); Console.WriteLine(seasonDisplayName?.Name ?? "Unknown"); // 使用空合并运算符处理可能为null的情况 } } public enum Season { [Display(Name = "It's autumn")] Autumn, [Display(Name = "It's winter")] Winter, [Display(Name = "It's spring")] Spring, [Display(Name = "It's summer")] Summer }</code>
The above is the detailed content of How to Retrieve Enum Display Names in ASP.NET MVC Razor Views?. For more information, please follow other related articles on the PHP Chinese website!