MVC+knocKout.js 实现下拉框级联
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MVC+knocKout.js 实现下拉框级联相关的知识,希望对你有一定的参考价值。
数据库:部门表和员工表
在控制器里面的操作:
1 public ActionResult Index3() 2 { 3 ViewBag.departments = new SelectList(getDepartments(),"d_id","d_name");//部门数据 4 return View(); 5 } 6 7 private List<department> getDepartments() 8 { 9 List<department> list = db.department.ToList(); 10 return list; 11 } 12 13 public JsonResult GetEmployye(int departmentId) 14 { 15 //通过部门id,获取该部门的员工 16 var list= db.employee.Where(a => a.e_d_id == departmentId).ToList().Select(a => new SelectListItem(){Text = a.e_name,Value = a.e_id+""}); 17 18 19 return Json(list,JsonRequestBehavior.AllowGet); 20 }
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 实现下拉框级联的主要内容,如果未能解决你的问题,请参考以下文章
使用 knockout.js 和 select2 级联下拉菜单