2

I am trying to convert my Items from Enum to a dropdownlist .Please help

public enum Colors{ red,blue,green,yellow,orange,white,black,Teal,Custom } @Html.DropDownList("SelectedColourId", Model.ColourList, "(Select one Color)") 

My ViewModel is below

 myPageViewModel:BasicViewModel { ..... public IEnumerable<SelectListItem> ColourList{ get; set; } ......... } 

I am tried something like

myViewModel.ColourList = Enum.GetNames(typeof(Colors)).ToArray() .Select(e => new SelectListItem() { Text = e.item, Value = e.itemindex }); 

But I don't know how to get itemText and its correesponding Index .Its throwing errors

2 Answers 2

2

In the controller, initialize the ColourList array using the Enum GetNames static method and Linq:

myPageViewModel.ColourList = Enum.GetNames(typeof(Colors)) .Select(c => new SelectListItem() { Text = c, Value = c }) .ToArray(); 
Sign up to request clarification or add additional context in comments.

3 Comments

@Millar gah, forgot you can't set the values in the constructor. The above should work now.
But is there a way I can get Index of the item in palce of Value ?
@Millar sure, just use Value = (int)Enum.Parse(typeof(Colors), c)
0

to add the option in dropdown from enum use the below code:

 foreach (DropDownEnum enumValue in Enum.GetValues(typeof(DropDownEnum))) { model.SortOptions.Add(new SelectListItem() { Text = enumValue.ToString(), Value = url+enumValue.ToString(), Selected = false }); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.