1 public class DemoController : Controller
2 {
3 public ActionResult BindDropDownList()
4 {
5 List<SelectListItem> select1 = new List<SelectListItem>
6 {
7 new SelectListItem { Text = "内容", Value = "值" },
8 new SelectListItem
9 };
10
11 ViewData["select1"] = new SelectList(select1, "Value", "Text", "此处为默认项的值");
12
13 return View();
14 }
15 }
1 <%= Html.DropDownList("select1") %>
2. 从数据库或者数组中循环读取下拉列表项
1 public class DemoController : Controller
2 {
3 public ActionResult BindDropDownList()
4 {
5 string[] texts = new string[] { "一", "二", "三", n };
6 string[] values = new string[] { "1", "2", "3", n };
7
8 List<SelectListItem> select1 = new List<SelectListItem>();
9
10 for (int i = 0; i < texts.Length; i++)
11 {
12 select1.Add(new SelectListItem
13 {
14 Text = texts[i],
15 Value = values[i]
16 });
17 };
18
19 ViewData["select1"] = new SelectList(select1, "Value", "Text", "此处为默认项的值");
20
21 return View();
22 }
23 }
1 <%= Html.DropDownList("select1") %>
3. 从数据库中读取某表的所有下拉菜单列表项
1 public class DemoController : Controller
2 {
3 public ActionResult BindDropDownList()
4 {
5 List<CategoryEntiry> categories = Category.GetAll();
6
7 ViewData["Categories"] = new SelectList(categories, "ID", "Name");
8
9 return View();
10 }
11 }
1 // 首先将 ViewData 中的数据转化为 SelectList
2 <% SelectList categories = ViewData["Categories"] as SelectList; %>
3
4 // 然后才能输出
5 <%= Html.DropDownList("Category", categories) %>