ASP.NET Core by Patrik

Displaying enum as select list in ASP.NET Core

Some properties of model classes come as enums and we want to show Enum values in a select list. Sometimes we want enum element names but sometimes we want to use custom names or even translations.

Let’s define the enum and make it use DisplayAttribute and resource file.

public enum CustomerTypeEnum
{
    [Display(Name = "Companies")]
    PrivateSector,

    [Display(Name = "PublicSector", ResourceType = typeof(Resources.Common))]
    PublicSector,
            
    Internal
}

There are three different cases together now:

  1. Enum member with just a name
  2. Enum member with Display attribute and static name
  3. Enum member with Display attribute and resource file

Important thing: set resource modifier to Public.

Now use the Html.GetEnumSelectList() extension method to fill the select list with enum members. Notice the first empty selection (Select type …) as the only member of the select list.

<div class="form-group">
    <label asp-for="Type" class="control-label"></label>
    <select asp-for="Type" 
            class="form-control" 
            asp-items="Html.GetEnumSelectList<CustomerTypeEnum>()">
        option>Select type ...option>
    </select>
    <span asp-validation-for="Type" class="text-danger"><span>
<div>

When we run the application we can see that the select list is filled with enum members and ASP.NET Core respects DisplayAttribute with static name and resource files.

If you don’t have control over enum (enum is defined in already built assembly) then you can’t apply Display attribute to enum and you need some other solution to get values you need.

Wrapping up

ASP.NET Core has built-in Html.GetEnumSelectList() method we can use to turn enum members to select list items. The method is intelligent enough to support the Display attribute and therefore we can use custom names for enum members and even translations from resource files.

ASP.NET Core
Enum

Comments

Leave a Comment

All fields are required. Your email address will not be published.