1

I have been trying to get the value inside of [Display(Name = '')] to display with an integer input. I've tried what this post said to do but I'm getting errors - I think it's because I'm in .Net Core not Framework. Here is the code trying to display the display name:

@Enum.GetName(typeof(StateEnum), Timelineinfo.State) //Timelineinfo.State is an int

The enum (truncated because it's too long):

 public enum StateEnum
        {
            Alabama, Alaska, [Display(Name = "American Samoa")] AmericanSamoa, Arizona,
            Arkansas, California, Colorado, Connecticut, Delaware, 
            [Display(Name = "District of Columbia")] DistrictofColumbia, //continues onwards...
       }
Bubinga
  • 613
  • 12
  • 29

1 Answers1

2
string GetEnumDisplayName<T>(T value) where T : Enum
{
    var fieldName = Enum.GetName(typeof(T), value);
    var displayAttr = typeof(T)
        .GetField(fieldName)
        .GetCustomAttribute<DisplayAttribute>();
    return displayAttr?.Name ?? fieldName;
}

Then invoke it like:

var displayName = GetEnumDisplayName(StateEnum.AmericanSamoa);

EDIT If Timelineinfo.State is an integer, you can use invoke:

var displayName = GetEnumDisplayName((StateEnum)Timelineinfo.State);
denys-vega
  • 3,522
  • 1
  • 19
  • 24
  • Thanks for the answer. This would work except I wouldn't be able to just say "AmericanSamoa" for example. The thing that goes after StateEnum would change depending on what page I am on. However, I can get what goes there by doing ```@Enum.GetName(typeof(StateEnum), Timelineinfo.State)``` Is there someway I can do something like: ```GetEnumDisplayName(StateEnum.Enum.GetName(typeof(StateEnum), Timelineinfo.State)```? – Bubinga Jul 15 '20 at 05:10
  • @Bubinga is `Timelineinfo.State` an `StateEnum` value? If so, then you can call `GetEnumDisplayName(Timelineinfo.State)` – denys-vega Jul 15 '20 at 05:25
  • @Bubinga I've edited my answer. Please check it out. – denys-vega Jul 15 '20 at 05:30
  • Sorry, Timelineinfo.State is an int. – Bubinga Jul 15 '20 at 05:34
  • @Bubinga check the edit. `GetEnumDisplayName((StateEnum)Timelineinfo.State)` – denys-vega Jul 15 '20 at 05:35
  • lol, I put in your edited code wrong. It works, thanks! :D – Bubinga Jul 15 '20 at 05:36