Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind <select> values to the name of each item in an enum in ASP.NET Core MVC?

I have an enum of some countries:

public enum Countries
{
    USA,
    Canada,
    Mexico,
}

I then have a property on my model:

[Required]
public string Country { get; set; }

In my view I have:

@Html.DropDownList("Country", Html.GetEnumSelectList(typeof(Countries)) ...)

I would like the value of each option in the generated select to be the name of each item from the Countries enum. By default, the value is a zero-based integer.

like image 858
mariocatch Avatar asked Apr 28 '16 14:04

mariocatch


People also ask

What is SelectListItem MVC?

SelectListItem is a class which represents the selected item in an instance of the System. Web. Mvc.

What is enum in asp net core?

An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members: C# Copy.

What is enum in ASP NET MVC?

In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer values.


1 Answers

The values are zero-based integers because you've asked for an EnumSelectList, which outputs an enum (ie the int values).

Instead, you can get the list of enum names, something like:

@Html.DropDownList("Country", new SelectList(Enum.GetNames(typeof(Countries))) ... )
like image 140
freedomn-m Avatar answered Nov 23 '22 18:11

freedomn-m