在最近的开发过程当中,应用了一些关于knockout的下拉项目。数组
关于下拉多选的开发在这里作一个记录。post
下面直接上代码ui
添加的时候,无需给初始值this
--viewmodel
function ViewModel() { //岗位下拉绑定 this.postName = ko.observableArray([]); };
添加了一个触发。根据部门得到对应的岗位spa
//根据部门ID去得到对应的岗位下拉选项 function jsSearchData(obj) { var depId = $(obj).val(); if ($.trim(depId) != "") { console.log("type=" + depId); $.getJSON("@Url.Action("Json_GetSelectPostAccordingToDepartmentId")", { DepartmentId: depId }, function (data) { viewModel.postName(data); }); } else { viewModel.postName([]); $("select[name=PostName]").trigger("change"); } }
@Html.DropDownList("DepartmentId", ViewBag.DepartmentId as SelectList, new { @class = "select2 required", onchange = "jsSearchData(this);", @style = "width:120px;" })
<select data-bind="options:$root.postName,optionsText:'Text',optionsValue:'Value'" style="width:200px;" class="select2" name="PostName" multiple></select>
后台得到对应的数据code
/// <summary> /// 根据部门ID得到对应全部的岗位 /// </summary> /// <param name="DepartmentId"></param> /// <returns></returns> public ActionResult Json_GetSelectPostAccordingToDepartmentId(int? DepartmentId) { var list = new DepartmentJobService().FindAll(x => x.DEPARTMENT_ID == DepartmentId).Select(x => new SelectListItem() { Value = x.NAME, Text = x.NAME }); return Json(list, JsonRequestBehavior.AllowGet); }
编辑的时候,须要把对应绑定的值初始化blog
其余代码都同样,我这里只给初始化的代码ip
function ViewModel() {
//这里传进来的参数相似于"行政助理,行政前台"这样的一个字符串,按逗号给他分割成一个数组。这个数组的组成就是select下拉的初始值 this.ownDepartmentSelectedOptions = ko.observableArray("@ownDepartmentPostName".split(",")); };
<select data-bind="options:postName,optionsText:'Text',optionsValue:'Value',selectedOptions:ownDepartmentSelectedOptions" style="width:200px;" class="select2" name="PostName" multiple></select>
关于下拉多选(multiple)给初始值,是由selectedOptions进行绑定的。把须要绑定的初始值序列化成数组绑定上去就能够了。初始化后的结果相似下面这个。开发
关于基本的绑定那些我就略过了,大概功能代码就是这些了。字符串