讓enum變成view來使用好像滿頻繁的,記錄一下擴充dropdownlist
public static MvcHtmlString DropDownEnumList<T>(this HtmlHelper htmlHelper, string name, string selectValue) where T : struct, IConvertible { return htmlHelper.DropDownList(name, GetSelectEnumListItems<T>(selectValue)); } public static MvcHtmlString DropDownEnumList<T>(this HtmlHelper htmlHelper, string name,string selectValue, object htmlAttributes) where T : struct, IConvertible { return htmlHelper.DropDownList(name, GetSelectEnumListItems<T>(selectValue), htmlAttributes); } public static MvcHtmlString DropDownEnumList<T>(this HtmlHelper htmlHelper, string name,string selectValue, IDictionary<string, object> htmlAttributes) where T : struct, IConvertible { return htmlHelper.DropDownList(name, GetSelectEnumListItems<T>(selectValue), htmlAttributes); } public static MvcHtmlString DropDownEnumList<T>(this HtmlHelper htmlHelper, string name,string selectValue, string optionLabel) where T : struct, IConvertible { return htmlHelper.DropDownList(name, GetSelectEnumListItems<T>(selectValue), optionLabel); } public static MvcHtmlString DropDownEnumList<T>(this HtmlHelper htmlHelper, string name, string selectValue, string optionLabel, object htmlAttributes) where T : struct, IConvertible { return htmlHelper.DropDownList(name, GetSelectEnumListItems<T>(selectValue), optionLabel, htmlAttributes); } public static MvcHtmlString DropDownEnumList<T>(this HtmlHelper htmlHelper, string name,string selectValue, string optionLabel, IDictionary<string, object> htmlAttributes) where T : struct, IConvertible { return htmlHelper.DropDownList(name, GetSelectEnumListItems<T>(selectValue), optionLabel, htmlAttributes); } public static IEnumerable<SelectListItem> GetSelectEnumListItems<T>(string selectValue) where T : struct, IConvertible { List<SelectListItem> items = new List<SelectListItem>(); foreach (var e in Enum.GetNames(typeof(T))) { string val = ((int)Enum.Parse(typeof(T), e)).ToString(); var selectlistItem = new SelectListItem() { Text = e, Value = val }; if (!string.IsNullOrWhiteSpace(selectValue) && (val == selectValue)) { selectlistItem.Selected = true; } items.Add(selectlistItem); } return items; }