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
});
}

3 comments:

  1. Got useful information about convert dictionary object to system.

    Convert ASP to ASP.Net

    ReplyDelete
  2. An iOS dev course helps learners master mobile development techniques. It focuses on structured learning and practice. This ios dev course supports skill enhancement. It is reliable.

    ReplyDelete
  3. Excellent insight! Our ui ux design course
    focuses on user-centered design with real-world projects.

    ReplyDelete