Showing posts with label binding to DropDownList in asp.net mvc. Show all posts
Showing posts with label binding to DropDownList in asp.net mvc. Show all posts

Wednesday, December 14, 2011

Convert Dictionary object to System.Web.MVC.SelectListItem



Scenario - In ASP.NET MVC, you need Enumberable of SelectListItem object to bind to a DropDownList. But you have a dictionary object of Lookup values from DB. What is the best way to convert dictionary to Enumberable of SelectListItem.

Solution - Create an Extension method ToSelectListItems() which will convert the dictionary object to Enumberable of SelectListItem as follows:


public static IEnumerable ToSelectListItems(this IDictionary items, string selected = "1")
{
return items.Select(k =>
new SelectListItem
{
Selected = (k.Value == selected),
Text = k.Key,
Value = k.Value
});
}