Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum for dropdown list in ASP.NET MVC Core

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?

like image 244
David Sharpe Avatar asked Jan 19 '17 11:01

David Sharpe


People also ask

What is enum in ASP NET MVC?

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.


1 Answers

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> 
like image 65
Kostas Avatar answered Oct 24 '22 15:10

Kostas