i have an asp.net-mvc webpage and i want to show a dropdown list that is based off an enum. I want to show the text of each enum item and the id being the int value that the enum is associated with. Is there any elegant way of doing this conversion?
The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.
You can use LINQ:
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem { Text = v.ToString(), Value = ((int)v).ToString() }).ToList();
Since MVC 5.1, the most elegant way would be to use EnumDropDownListFor method of Html helper if you need to populate select
options in your view:
@Html.EnumDropDownListFor(m => m.MyEnumProperty,new { @class="form-control"})
or GetSelectList method of EnumHelper in your controller:
var enumList = EnumHelper.GetSelectList(typeof (MyEnum));
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