string deptId =Request.Form["depts"].Trim();
Html.DropDownList()赋默认值:
页面代码如下:
<%
List<SelectListItem> list = new List<SelectListItem> {
new SelectListItem { Text = "启用", Value = "0",Selected = true},
new SelectListItem { Text = "禁用", Value = "1" } };
%>//list储存dropdownlist的默认值
<%=Html.DropDownList("state",list,Model.state) %> //state为实体的属性,默认选中"启用"
Html.DropDownList()从数据库读取值:
页面代码如下:
<%= Html.DropDownList("Category", ViewData["Categories"] as SelectList,"--请选择--",new { @class = "my-select-css-class" } )%>
Controllers代码:
public ActionResult Create()
{
List<Category> categories = categoryService.GetAll();
ViewData["Categories"] = new SelectList(categories, "Id", "Name");
return View();
}
public static string DropDownList(this HtmlHelper htmlHelper, string name)
{
IEnumerable<SelectListItem> selectData = htmlHelper.GetSelectData(name);
return htmlHelper.SelectInternal(null, name, selectData, true, false, null);
}
第一种方式: List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem() { Text = "001", Value = "1", Selected = false });
items.Add(new SelectListItem() {Text = "002", Value = "2", Selected = false });
ViewData["items"] = items;
简化后:
var items = new List<SelectListItem>()
{
(new SelectListItem() {Text = "001", Value = "1", Selected = false}),
(new SelectListItem() {Text = "002", Value = "2", Selected = false})
};
将items值给ViewData:
ViewData["items"] = items;
在aspx中这样使用:
<%= Html.DropDownList("items") %>
生成的代码中,items将作为<select>标签的name和id值。
public static string DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList) { return htmlHelper.DropDownList(name, selectList, null); }
使用方法:
<%= Html.DropDownList("items", new List<SelectListItem> { (new SelectListItem() {Text = "001", Value = "1", Selected = false}), (new SelectListItem() {Text = "002", Value = "2", Selected = false}) })%>
在这里,不需要ViewData传入值,第一个参数items作为标签的name和id的值。items也可以是任意的字符串。
public static string DropDownList(this HtmlHelper htmlHelper, string name, string optionLabel) { IEnumerable<SelectListItem> selectData = htmlHelper.GetSelectData(name); return htmlHelper.SelectInternal(optionLabel, name, selectData, true, false, null); }
使用方法和第一种原型相同,string optionLabel作为一个缺省的空的选项。这样可以完成加入不需要选取任何选项的场景。