I got a model defined as IEnumerable<MyViewModel> which I tried to use to create a select list (Html.SelectListFor). But I couldn’t figure out how to do it. Which made me look at the plain Html.SelectList method.
Since it wants a IEnumerable<SelectListITem> and I don’t want to add view specific logic in my controller or logic in my view I ended up to create the following extension method:
public static class ExtensionMethods
{
public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> items, Func<T, string> valueSelector, Func<T, string> textSelector)
{
return items.Select(item => new SelectListItem
{
Text = textSelector(item),
Value = valueSelector(item)
}).ToList();
}
}
Which I use as:
@Html.DropDownList("trainid", Model.ToSelectList(item => item.Id, item => item.Name));
This doesn’t seem to be the optimal solution. How should I have done?
Guess that the answer is that I’m already using the best solution.