ASP.NET MVC中使用DropDownList控件方法(2)
ASP.NET MVC为DropDownList和ListBox(都在html中使用select标记)准备了一个辅助类型:SelectList。SelectList继承自MultiSelectList,而后者实现了IEnumerable<SelectListItem>。也就是说,SelectList可以直接作为Html.DropDownList方法的第二个参数。
MultiSelectList包含四个属性,分别为:
- Items:用于在select标记中出现的列表,通常使用option标记表示。IEnumerable类型。
- DataTextField:作为option的text项,string类型。
- DataValueField:作为option的value项,string类型。
- SelectedValues:选中项的value值,IEnumerable类型。
显然,作为DropDownList来说,选中项不可能为IEnumerable,因此SelectList提供了一个新的属性:
- SelectedValue:选中项的value值,object类型。
同时,SelectList的构造函数如下所示:
public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue) : base(items, dataValueField, dataTextField, ToEnumerable(selectedValue)) { SelectedValue = selectedValue; }
于是我们的代码变为:
var users = GetUsers(); var selectList = new SelectList(users, "Age", "Name", "24"); this.ViewData["list"] = selectList;
<%=Html.DropDownList("list")%>
当然,你也可以使用不带selectedValue参数的构造函数重载,而在view中显式指定IEnumerable<SelectListItem>,并在ViewData或view model中指定其他与DropDownList同名的项作为默认选项。
最后让我们来回顾一下DropDownList的三种用法:
- 建立IEnumerable<SelectListItem>并在其中指定默认选中项。
- 建立IEnumerable<SelectListItem>,在单独的ViewData项或view model的属性中指定默认选中项。
- 使用SelectList。
好了,关于DropDownList的用法我们今天就讨论到这里,您会用了吗?