与MVC3相比,差别很大:
表现形式一:
public ActionResult Main() { List<SelectListItem> items = new List<SelectListItem>(); items.Add(new SelectListItem { Text = "Action", Value = "0" }); items.Add(new SelectListItem { Text = "Comedy", Value = "2" }); ViewBag.MovieType = items; return View(); }
<h2>@Html.DropDownList("MovieType")</h2>
表现形式二:
public enum Unit { 吨, 堆, 捆 } var values = Enum.GetValues(typeof(Unit)).Cast<Unit>(); var items = from value in values select new SelectListItem { Text = value.ToString(), Value = value.ToString()., Selected = value == Unit.堆 };
@Html.DropDownList("MovieType")
使用方法扩展:
/// <summary> /// 在MVC开发中我们常常用到枚举类型,通常枚举类型在使用中是是用DropDownList,每次转换不是什么好办法。 通过扩展加以实现此功能。 /// </summary> public static class ExSelectListItem { public static IEnumerable<SelectListItem> ToSelectListItem(this Enum valueEnum) { var values = Enum.GetValues(valueEnum.GetType()); var result= from int value in values select new SelectListItem { Text =Enum.GetName(valueEnum.GetType(),value), Value = value.ToString() }; return result; } public static List<SelectListItem> ToSelectListItem(this Enum valueEnum, string selectName) { return (from int value in Enum.GetValues(valueEnum.GetType()) select new SelectListItem { Text = Enum.GetName(valueEnum.GetType(), value), Value = Enum.GetName(valueEnum.GetType(), value), Selected = Enum.GetName(valueEnum.GetType(), value) == selectName ? true : false }).ToList(); } }
var items = Unit.堆.ToSelectListItem("捆"); ViewBag.Unit = items;
表现形式三(编辑、更新有默认值):
//下拉菜单 List<SelectListItem> list = new List<SelectListItem>() { new SelectListItem(){Value="Man",Text="Man"}, new SelectListItem(){Value="Female",Text="Female"} }; ViewBag.Gender = new SelectList(list, "Value", "Text",entity.Gender);
@Html.DropDownList("Gender", null, new { @class = "form-control" })
学习交流群:364976091