ASP.NET MVC DropDownList 用法
时间:2011-05-01 来源:露水丛生
一: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) %>
摘自 http://blog.sina.com.cn/s/blog_69cfe5430100o2me.html