public enum Avbc
{
Red=1,
Blue=2,
Whilt=3,
Black=4
}
public static class EmumHelper { public static SelectList GetSelectListByEnum<TEnum>(this TEnum enumObj, int? selectedItem = null) { if (Enum.GetValues(typeof(TEnum)).Length > 0) { List<SelectListItem> listResult = new List<SelectListItem>(); foreach (TEnum e in Enum.GetValues(typeof(TEnum))) { if (selectedItem!=null && selectedItem == Convert.ToInt32(e)) // 選中 { SelectListItem item = new SelectListItem { Value = Convert.ToInt32(e).ToString(), // 傳輸值 Text = e.ToString(), // 顯示值 Selected = true }; listResult.Add(item); } else { SelectListItem item = new SelectListItem // 不選中 { Value = Convert.ToInt32(e).ToString(), // 傳輸值 Text = e.ToString() // 顯示值 }; listResult.Add(item); } } if (selectedItem != null) return new SelectList(listResult, "Value", "Text",selectedItem); else return new SelectList(listResult, "Value", "Text"); } return null; } }
Controller調用 Avbc.Black是枚舉中隨便一個項,擴展方法中會根據這個項找到這個枚舉,而後所有列出this
ViewBag.avbc = Avbc.Black.GetSelectListByEnum();
View強類型調用spa
@Html.DropDownListFor(m => m.avbc, ViewBag.avbc as SelectList, Model.avbc)