4:MVC学习——Html.DropDownList绑定数据
先看效果图:
再看Controller的ddl绑定代码:
public ActionResult Index()
{
//绑定DropDownList数据
List<ClassInfo> classList = new List<ClassInfo>();
ClassInfo classinfo = new ClassInfo { ClassId = 0, ClassName = "全部" };
classList.Add(classinfo);
List<ClassInfo> classList2 = new ClassManager().getClassInfo();
classList.AddRange(classList2);
SelectList selectList = new SelectList(classList, "ClassId", "ClassName", "0");
ViewBag.ClassInfo = selectList;
return View();
}
new SelectList(classList, "ClassId", "ClassName", "0"):第三个参数代表默认选择值;
再看view的index页面:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>学生列表</title>
</head>
<body>
<div>
欢迎 @Session["AdminName"].ToString() 的到来!
<a href="/Admin/LoginOut">登出</a>
</div>
<div>
学生姓名: <input type="text" id="txt_studentName" name="txt_studentName" />
所在班级: @Html.DropDownList("ddl_ClassInfo",ViewBag.ClassInfo as SelectList )
<input type="button" id="btn_search" value="查询" onclick="getStudentQBE()" />
</div>
<div>
<table id="studentList">
</table>
<div id="pager">
</div>
</div>
</body>
</html>
此处要注意一点的是:DropDownList的id(ddl_ClassInfo)不能跟ViewBag(ClassInfo)的重名,不然会出错。