Use this extension method to create a drop-down list from the source (select all values projecting onto the key and value). Example
public static IEnumerable<SelectListItem> ToDropDown<TSource>(this IEnumerable<TSource> source, Func<TSource, string> keySelector, Func<TSource, string> elementSelector, Func<TSource,bool> selected) { if (source == null) { return new List<SelectListItem>(); } return source.Select(c => new SelectListItem { Value = keySelector(c), Text = elementSelector(c), Selected = selected(c) }).ToList(); }
fill in your viewBag
ViewBag.Languages = languageRepository().GetAll().ToList().ToDropDown(c => c.ID, c => c.Description, c => c.ID == "EN");
and finally a razor
@Html.DropDownList("ddLanguages", (IEnumerable<SelectListItem>)ViewData.Languages, "Please Select")
source share