Successfully added
ASP.NET Core
by Patrik
ASP.NET Core - Displaying enum as select list in ASP.NET Core
Let’s say that you have class Person
and one of its properties is enum (in our case it’s enum Gender
).
public enum Gender { Unknown, Male, Female }
Below you can see Razor Page with a simple HTML form. Please remember to add the using statement to the folder where is defined your enum type (in my case it’s @using SelectBindingEnum.Models
).
<div class="form-group"> <label asp-for="Person.Gender" class="control-label"></label> <select asp-for="Person.Gender" asp-items="Html.GetEnumSelectList<Gender>()" class="form-control"></select> <span asp-validation-for="Person.Gender" class="text-danger"></span> </div>
As you can see above to binding enum values to HTML select tag you should use Tag Helper asp-items
and HtmlHelper method GetEnumSelectList<T>
where T
is an enum type. This method generates a SelectList object for all enum values. Also, this method allows you to add Display
attribute to your enum to change display text.
public enum Gender { [Display(Name = "None")] Unknown, Male, Female }
If you would add this attribute, you will see the following values in HTML select tag: None, Male and Female.
Referenced in:
Comments