DorpDownListFor
1. 直接在页面初始化
@Html.DropDownListFor(model => model.Status, new SelectList(new string[] {"正常", "暂停销售"}))
2.ViewBag传递
@Html.DropDownListFor(model => model.CarCategoryID, (SelectList)ViewBag.CarCategory)
DropDownList
一:Html.DropDownList 数据绑定并选定默认项
1.建立IEnumerable<SelectListItem>并在其中指定默认选中项。
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;
然后在View中<%=Html.DropDownList("list")%>即可绑定数据,且选中第二项。
2.建立IEnumerable<SelectListItem>,在单独的ViewData项或view model的属性中指定默认选中项。
使用SelectList。
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Kirin", Value = "29" });
items.Add(new SelectListItem { Text = "Jade", Value = "28"});
items.Add(new SelectListItem { Text = "Yao", Value = "24"});
this.ViewData["list"] = items;
this.ViewData["selected"] = 24;
3.使用SelectList。
var users = GetUsers();
var selectList = new SelectList(users, "Age", "Name", "24");
this.ViewData["list"] = selectList;
<%=Html.DropDownList("list")%>
4.
List<SelectListItem> lsSelItem = new List<SelectListItem>();
SelectListItem sel = new SelectListItem();
sel.Value = "http://www.csdn.net";
sel.Text = "CSDN";
lsSelItem.Add(sel);
sel = new SelectListItem();
sel.Value = "http://www.nopchina.com";
sel.Text = "NopChina";
lsSelItem.Add(sel);
sel = new SelectListItem();
sel.Value = "http://blog.csdn.net/csdbfans";
sel.Text = "Csdbfans BLOG";
lsSelItem.Add(sel);
SelectList ddlSelData = new SelectList(lsSelItem.AsEnumerable(), "Value", "Text", "http://www.cnblogs.com");
ViewData["ddlTestData"] = ddlSelData;
<%=Html.DropDownList("ddlTest",ViewData["ddlTestData"] as SelectList) %>