In this post, you will see how to bind enum to HTML select tag. Let’s say that you have class Person
and one of its properties is enum (in our case it’s enum Gender
).
namespace SelectBindingEnum.Models
{
public enum Gender
{
Unknown,
Male,
Female
}
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Gender Gender { get; set; }
}
}
Below you can see Razor Page with a simple HTML form to create a new person. Please remember to add the using statement to the folder where is defined your enum type (in my case it’s @using SelectBindingEnum.Models
).
@page
@using SelectBindingEnum.Models
@model SelectBindingEnum.CreateModel
<h1>Create</h1>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Person.FirstName" class="control-label"></label>
<input asp-for="Person.FirstName" class="form-control" />
<span asp-validation-for="Person.FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Person.LastName" class="control-label"></label>
<input asp-for="Person.LastName" class="form-control" />
<span asp-validation-for="Person.LastName" class="text-danger"></span>
</div>
<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>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</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.