Skip to content

Instantly share code, notes, and snippets.

@pagebrooks
Created December 7, 2012 00:50
Show Gist options
  • Save pagebrooks/4229811 to your computer and use it in GitHub Desktop.
Save pagebrooks/4229811 to your computer and use it in GitHub Desktop.
ASP.NET MVC Html Helper for generating a select list from a dictionary
public static List<SelectListItem> ToSelectList(this Dictionary<string, string> items, string defaultItem, bool insertBlankItem = false)
{
string[] defaultItems = new[] { defaultItem };
if (!string.IsNullOrWhiteSpace(defaultItem))
{
defaultItems = defaultItem.Split(',');
}
var i = items.Select(pair => new SelectListItem
{
Text = pair.Value,
Value = pair.Key,
Selected = defaultItems.Contains(pair.Key)
}).ToList();
if (insertBlankItem)
{
i.Insert(0, new SelectListItem());
}
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment