首页 > 代码库 > MVC+knocKout.js 实现下拉框级联

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 = http://www.mamicode.com/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 实现下拉框级联