在最近的开发过程中,应用了一些关于knockout的下拉项目。
关于下拉多选的开发在这里做一个记录。
下面直接上代码
添加的时候,无需给初始值
--viewmodel
function viewmodel() { //岗位下拉绑定 this.postname = ko.observablearray([]); };
添加了一个触发。根据部门获得对应的岗位
//根据部门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>
后台获得对应的数据
/// <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); }
编辑的时候,需要把对应绑定的值初始化
其他代码都一样,我这里只给初始化的代码
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进行绑定的。把需要绑定的初始值序列化成数组绑定上去就可以了。初始化后的结果类似下面这个。
关于基本的绑定那些我就略过了,大概功能代码就是这些了。