Friday, January 13, 2012

Code: Convert Enum to MVC SelectList


public static class EnumHelper
{
    public static List<SelectListItem> GetSelectList<TEnum>(params TEnum[] ignoreList)
    {
        List<SelectListItem> enumList = new List<SelectListItem>();
        foreach (TEnum data in Enum.GetValues(typeof(TEnum)))
        {
            if (!ignoreList.Contains(data))
            {
                enumList.Add(new SelectListItem
                {
                    Text = data.ToString().Replace("_"" "),
                    Value = ((int)Enum.Parse(typeof(TEnum), data.ToString())).ToString()
                });
            }
        }
 
        return enumList;
    }
}




CommunicationList = EnumHelper.GetEnumSelectList<CommunicationTypes>();
@Html.DropDownList("CommunicationType", Model.CommunicationList)
You'll notice my method replaces underscores with a space. Since Enums cant have spaces this allows you to have nicely formatted text in your UI without extra work.  I chose to return a List of SelectListItem instead of a SelectList so that my ViewModels can modify the list if necessary.