在最近的開發過程當中,應用了一些關於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進行綁定的。把須要綁定的初始值序列化成數組綁定上去就能夠了。初始化後的結果相似下面這個。開發
關於基本的綁定那些我就略過了,大概功能代碼就是這些了。字符串