与MVC3相比,差别很大:
表现形式一:
public ActionResult Main() { Listitems = new List (); items.Add(new SelectListItem { Text = "Action", Value = "0" }); items.Add(new SelectListItem { Text = "Comedy", Value = "2" }); ViewBag.MovieType = items; return View(); }
@Html.DropDownList("MovieType")
表现形式二:
public enum Unit{ 吨, 堆, 捆}var values = Enum.GetValues(typeof(Unit)).Cast();var items = from value in values select new SelectListItem { Text = value.ToString(), Value = value.ToString()., Selected = value == Unit.堆 };
@Html.DropDownList("MovieType")
使用方法扩展:
////// 在MVC开发中我们常常用到枚举类型,通常枚举类型在使用中是是用DropDownList,每次转换不是什么好办法。 通过扩展加以实现此功能。/// public static class ExSelectListItem{ public static IEnumerableToSelectListItem(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 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;
表现形式三(编辑、更新有默认值):
//下拉菜单 Listlist = new List () { 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" })