DropDownList数据绑定
在控制器中Controller中,为前台页面DropDownList准备的数据
List<bookInfo> bookList = bookManger.GetbookInfo();
List<SelectListItem> deptSelectItems = new List<SelectListItem>(); deptSelectItems.Add(new SelectListItem() { Text = "请选择", Value = "-1", Selected = true }); foreach (bookInfo b in bookList) { SelectListItem item = new SelectListItem(); item.Text = b.bookname; item.Value =Convert.ToString(b.bookId); item.Selected = false; deptSelectItems.Add(item); } ViewData["depBooks"] = deptSelectItems;
在页面代码中,
var dept = (List<SelectListItem>)ViewData["depBooks"];
@Html.DropDownList("ddlBooks", dept) ddlBooks为DropDownList定义的ID
或@Html.DropDownList("depBooks") id写成与ViewData定义的一个样