0

I am developing a web application and .NET Core and recently bumped against this issue.

It shows the Id of the enum value in: @Html.DisplayFor(model => model.MutatieReden) but I want to show the name for the enum as this is a 'Details' view.

My enum is built like this, am I missing something?:

//Class property
public Reden? MutatieReden { get; set; }

//Enum
    public enum Reden
    {
        [Display(Name = "Niet van toepassing")] NietVanToepassing = 1,
        [Display(Name = "Administratieve reden")] AdministratieveReden = 2,
        [Display(Name = "Niet akkoord klant")] NietAkkoordKlant = 3,
        [Display(Name = "Incasso blokkade")] IncassoBlokkade = 4,
    }

I tried various solutions but most of them were for regular ASP.NET MVC and answers were all outdated.

EDIT: This is not a duplicate as this is for ASP.NET Core and the other solutions are for .NET MVC 5.1. Tried these solutions already.

Aids Jung
  • 63
  • 1
  • 7
  • Show us two of the approaches you tried. In your question. – mjwills Jun 11 '19 at 11:27
  • By "name" here, do you actually mean `"Niet van toepassing"` etc? – Marc Gravell Jun 11 '19 at 11:29
  • @MarcGravell yes, I want to show these values instead of the Id its giving me – Aids Jung Jun 11 '19 at 11:29
  • @AidsJung , I tried to reproduce the issue with ASP.NET Core MVC 2.2 ,but the name of Display attribute showed well . [Here](https://microsoftapc-my.sharepoint.com/:u:/g/personal/v-xuelc_microsoft_com/EWBkn0TDA5BGoL1Qf18HLEgBAumDSFGhj7SEPZUj1kh4iQ?e=ddSEVv) is my test demo , you could check for the difference . If you could share the reproducible demo, it would help us provide effective suggestion. – Xueli Chen Jun 12 '19 at 02:45

2 Answers2

4

For display purpose, I think we can use:

@Html.Display(Model.MutatieReden.GetDisplayName())

Or you even can create extra properties for display only:

public string MutatieRedenText { get => this.MutatieReden.GetDisplayName(); }

Add this static method into a static class like public static class EnumHelper

public static string GetDisplayName(this Enum val)
    {
        return val.GetType()
                  .GetMember(val.ToString())
                  .FirstOrDefault()
                  ?.GetCustomAttribute<DisplayAttribute>(false)
                  ?.Name
                  ?? val.ToString();
    }

PS: I haven't tested with compiler but it probably works

Hieu Le
  • 1,042
  • 8
  • 18
  • According to [this](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.displayattribute.name?view=net-5.0) : _"Do not use this property to get the value of the Name property. Use the GetName method instead."_ However, that method will throw an exception if the attribute has not been set. – JHBonarius Aug 22 '21 at 11:49
1

There's no need in Display attribute at all:

Reden enum_value = Reden.AdministratieveReden;
string enum_name = Enum.GetName(typeof(Reden), enum_value);
JohnyL
  • 6,894
  • 3
  • 22
  • 41