MVC+knocKout.js 实现下拉框级联

时间:2021-09-30 12:42:38

数据库:部门表和员工表

MVC+knocKout.js 实现下拉框级联MVC+knocKout.js 实现下拉框级联

在控制器里面的操作:

 public ActionResult Index3()
{
ViewBag.departments = new SelectList(getDepartments(),"d_id","d_name");//部门数据
return View();
} private List<department> getDepartments()
{
List<department> list = db.department.ToList();
return list;
} public JsonResult GetEmployye(int departmentId)
{
//通过部门id,获取该部门的员工
var list= db.employee.Where(a => a.e_d_id == departmentId).ToList().Select(a => new SelectListItem(){Text = a.e_name,Value = a.e_id+""}); return Json(list,JsonRequestBehavior.AllowGet);
}

html里面的实现:

@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/knockout-2.2.0.debug.js"></script>
<title>Index3</title>
</head>
<body>
<div>
<p>选择部门:@Html.DropDownList("department",ViewBag.departments as SelectList,"请选择",new{onchange="searchEmployee();"})
</p>
<p data-bind="visible: selectOptions().length > 0"></p>
<b style="color:#0094ff">员工:</b>
<select data-bind="options: selectOptions, optionsText: 'Text', optionsValue: 'Value', optionsCaption: '请选择'"></select>
</div>
</body>
<script type="text/javascript">
function ViewModel() {
this.selectOptions = ko.observableArray([]); } var vm = new ViewModel();
ko.applyBindings(vm); function searchEmployee() {
var id = $("#department").val();
$.getJSON(
"@Url.Action("GetEmployye")",
{ departmentId: id },
function (data) {
vm.selectOptions(data);
});
}
</script>
</html>

效果:MVC+knocKout.js 实现下拉框级联