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.
SelectListItem is a class which represents the selected item in an instance of the System. Web. Mvc.
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.
In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer values.
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))) ... )
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