In the recent development process, some drop-down projects about knockout have been applied.
Make a record here about the development of drop-down and multi selection.
Here's the code
When adding, there is no need to give the initial value
--viewmodel
function ViewModel() { //Position drop-down binding this.postName = ko.observableArray([]); };
Added a trigger. Obtain corresponding positions according to the Department
//Get the corresponding position drop-down options according to the Department 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>
Get the corresponding data in the background
/// <summary> ///Obtain all corresponding positions according to department 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); }
When editing, you need to initialize the value of the corresponding binding
All other codes are the same. I only give initialization code here
function ViewModel() {
//The parameter passed in here is similar to a string like "administrative assistant, administrative foreground", which is divided into an array by comma. The composition of this array is the initial value of the select drop-down 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>
As for the initial value of multiple drop-down, it is bound by selectedOptions. The initial value to be bound is serialized into an array and bound. The result after initialization is similar to the following one.
I've skipped the basic binding, which is probably the function code.