转自:
http://www.cnblogs.com/guanjie20/archive/2010/12/09/1901056.html
DropDownList则与TextBox等控件不同,它使用的是select标记。它需要两个值:在下拉框中显示的列表,和默认选项。而自动绑定一次只能绑定一个属性,因此你需要根据需要选择是绑定列表,还是默认选项。
DropDownList扩展方法的各个重载版本“基本上”都会传递到这个方法上:
public static string DropDownList(
this HtmlHelper htmlHelper,
string name,
IEnumerable<SelectListItem> selectList,
string optionLabel,
IDictionary<string, object> htmlAttributes) {
}
this HtmlHelper htmlHelper,
string name,
IEnumerable<SelectListItem> selectList,
string optionLabel,
IDictionary<string, object> htmlAttributes) {
}
如果没有指定selectList,该方法将自动绑定列表,即从ViewData中查找name所对应的值。如果提供了selectList,将自动绑定默认选项,即从selectList中找到Selected属性为true的SelectedListItem。(具体参见HtmlHelper方法的SelectInternal辅助方法)
例1:如果在Action方法中有如下代码:
在View中这样使用:
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Kirin", Value = "29" });
items.Add(new SelectListItem { Text = "Jade", Value = "28", Selected = true});
items.Add(new SelectListItem { Text = "Yao", Value = "24"});
this.ViewData["list"] = items;
items.Add(new SelectListItem { Text = "Kirin", Value = "29" });
items.Add(new SelectListItem { Text = "Jade", Value = "28", Selected = true});
items.Add(new SelectListItem { Text = "Yao", Value = "24"});
this.ViewData["list"] = items;