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?
The MVC framework sees the enum value as a simple primitive and uses the default string template. One solution to change the default framework behavior is to write a custom model metadata provider and implement GetMetadataForProperty to use a template with the name of "Enum" for such models.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With