Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an enumeration into a List<SelectListItem>?

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?

like image 667
leora Avatar asked Aug 15 '10 21:08

leora


People also ask

How do I turn an enum into a list?

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.


2 Answers

You can use LINQ:

Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem {     Text = v.ToString(),     Value = ((int)v).ToString() }).ToList(); 
like image 187
SLaks Avatar answered Sep 28 '22 08:09

SLaks


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)); 
like image 37
Maksim Vi. Avatar answered Sep 28 '22 08:09

Maksim Vi.