How to get the Display Name Attribute of an Enum member via MVC razor code?

后端 未结 20 2387
孤街浪徒
孤街浪徒 2020-11-22 09:30

I\'ve got a property in my model called \"Promotion\" that its type is a flag enum called \"UserPromotion\". Members of my enum have display attributes set as follows:

20条回答
  •  粉色の甜心
    2020-11-22 09:41

    For ASP.Net Core 3.0, this worked for me (credit to previous answerers).

    My Enum class:

    using System;
    using System.Linq;
    using System.ComponentModel.DataAnnotations;
    using System.Reflection;
    
    public class Enums
    {
        public enum Duration
        { 
            [Display(Name = "1 Hour")]
            OneHour,
            [Display(Name = "1 Day")]
            OneDay
        }
    
        // Helper method to display the name of the enum values.
        public static string GetDisplayName(Enum value)
        {
            return value.GetType()?
           .GetMember(value.ToString())?.First()?
           .GetCustomAttribute()?
           .Name;
        }
    }
    

    My View Model Class:

    public class MyViewModel
    {
        public Duration Duration { get; set; }
    }
    

    An example of a razor view displaying a label and a drop-down list. Notice the drop-down list does not require a helper method:

    @model IEnumerable 
    
    @foreach (var item in Model)
    {
        
        
    }

提交回复
热议问题