Asp.net MVC中的DropDownLists貌似会让一开始从Asp.net Forms转过来的程序员造成不少迷惑.这篇文章讲述了为了使用DropDownLists,你需要在Asp.Net MVC中知道的方方面面. DropDownList,ComboBox,无论你喜欢怎么称呼这些,他们毫无例外的会被生成为html select标签.在闭标签之间,每一个列表元素都必须被包裹于 为了简便起见,这里我先用一个静态的列表作为例子,你可以将这些作为html直接加入到你的View中: 或者,给列表加点小动态,假如需要列表的年份会随着新年到来之际自动往后推1年: 甚至可以更简便: <% for (var i = 0; i < 6; i++){%> <%}%> 上面三个代码段生成效果相同,如下:  如果的数据是来自数据库,那最好还是使用Html.DropDownList()扩展方法的八个重载方法来创建DropDownList.在这里我并不会一一说明这些不同的重载,但是会说明主要重载。第一种重载-public static string DropDownList(this HtmlHelper htmlHelper, string name) -仅仅接受一个string类型的参数.帮助文档中只是简单说明了这个string参数是 public ActionResult Index() { var db = new NorthwindDataContext(); IEnumerable items = db.Categories .Select(c => new SelectListItem { Value = c.CategoryID.ToString(), Text = c.CategoryName }); ViewData["CategoryID"] = items; return View(); } 注意每一个SelectListItem对象都必须给Value和Text属性进行赋值。他们会在运行时分别匹配到html的之间的内容。注意这里ViewData的key用“CategoryID”显得有点奇怪,但实际上CategoryID正式向服务器提交的值,所以使用这样的命名是有实际意义的。在View中,使用重载方法: <%= Html.DropDownList("CategoryID") %> 而对应生成的HTML如下: Html.DropDownList的第二种重载方法-public static string DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable selectList)-是经常被使用的。在这个重载中,你可以使用IEnumerable或者SelectList对象作为参数。首先再看返回上述两个对象的方法之前,先看在View中的代码: <%= Html.DropDownList("CategoryID", (IEnumerable) ViewData["Categories"]) %> 我们先说存入ViewData的第一种对象类型-IEnumerable对象,代码和前面的例子很像: public ActionResult Index() { var db = new NorthwindDataContext(); IEnumerable items = db.Categories .Select(c => new SelectListItem { Value = c.CategoryID.ToString(), Text = c.CategoryName }); ViewData["Categories"] = items; return View(); } 再看在ViewData中存入SelectList类型的代码: public ActionResult Index() { var db = new NorthwindDataContext(); var query = db.Categories.Select(c => new { c.CategoryID, c.CategoryName }); ViewData["Categories"] = new SelectList(query.AsEnumerable(), "CategoryID", "CategoryName"); return View(); }
|