JG,
funnily enogh, I should have found a similar article when looking for such a solution. I have an extn method that goes:
public static IList<SelectListItem> ToSelectItemList<T>( this IEnumerable<T> list, Func<T, string> textSelector, Func<T, string> valueSelector, T selected) where T : class { var results = new List<SelectListItem>(); if (list != null) { results.AddRange( list.Select(item => new SelectListItem { Text = textSelector.Invoke(item), Value = valueSelector.Invoke(item), Selected = selected != null ? selected.Equals(item) : false })); } return results; }
and called as:
<%: Html.DropDownList("Base.EntityRootID", Model.EntityRootList.ToSelectItemList(foo => foo.EntityName, foo => foo.ID.ToString(), Model.Base.EntityRoot))%>
how strange. I really like this method, since it is both general and using the object itself to compare the selected element with means that you are not ar $ e around with comparison id, etc.
works for me.
source share