Using enum for dropdown list in ASP.NET MVC Core

David Sharpe picture David Sharpe · Jan 19, 2017 · Viewed 58.1k times · Source

I'm trying to create a dropdown list with an enum property in ASP.NET MVC Core using the tag helper in a Razor view:

Here is the model:

public class PersonalMember : Member
{
    [Required, Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required, Display(Name = "Last Name")]
    public string LastName { get; set; }

    [EnumDataType(typeof(Gender))]
    public Gender GenderType { get; set; }
}

public enum Gender
{
    Male = 1,
    Female = 2
}

Here is part of a form in the view:

<div class="form-group">
    <label asp-for="GenderType" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <select asp-for="GenderType" asp-items="Html.GetEnumSelectList<GenderType>()">
            <option selected="selected" value="">Please select</option>
        </select>
        <span asp-validation-for="GenderType" class="text-danger" />
    </div>
</div>

The problem I'm having is that after Html.GetEnumSelectList, GenderType is not recognized and shows up as an error.

Does anyone know how to solve this?

Answer

Kostas picture Kostas · Feb 22, 2018

I think you accidentally used GenderType instead of Gender. The correct syntax is

<select asp-for="GenderType" asp-items="Html.GetEnumSelectList<Gender>()">
    <option selected="selected" value="">Please select</option>
</select>