标签:c style class blog code java
与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;
MVC4 下DropDownList使用方法,布布扣,bubuko.com
标签:c style class blog code java
原文地址:http://www.cnblogs.com/firstcsharp/p/3763790.html