javascript-在淘汰赛中Select2选择标签作为对象而不是’id’
作者:互联网
所以我有一个select2标签输入工作正常,正确显示标签,并将选定的ID存储到selectedProducts observableArray中.但是,我的HTTPPost期望一个对象数组,而不是整数数组.
我一直在寻找如何将select2另存为一个对象(即{id:1,text:“ abc”})而不是一个整数数组.
我的绑定如下:
<div class="col-sm-10">
<input type="hidden" id="tags" class="select2 form-control" multiple="multiple" data-bind="value: selectedProducts, select2: {tags: ko.toJS($parent.availableProducts), placeholder: 'select products'}" />
<pre data-bind="text: ko.toJSON(products, null, 2)"></pre>
</div>
var newItem = function (newitem) {
var self = this;
self.id = ko.observable();
self.selectedProducts = ko.observableArray();
self.products = ko.computed(function () {
return self.selectedProducts().split(',');
}, self);
}
var viewModel = function (data) {
var self = this;
self.newitem= ko.observable(new newItem());
self.availableProducts = ko.observableArray([]);
$.ajax({
type: "GET",
url: '/GetAllProducts',
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
success: function (data) {
ko.mapping.fromJS(data, {}, self.availableProducts);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
}
ko.bindingHandlers.select2 = {
init: function (element, valueAccessor, allBindingsAccessor) {
var obj = valueAccessor(),
allBindings = allBindingsAccessor(),
lookupKey = allBindings.lookupKey;
setTimeout(function () {
$(element).select2(obj);
}, 0);
if (lookupKey) {
var value = ko.utils.unwrapObservable(allBindings.value);
$(element).select2('data', ko.utils.arrayFirst(obj.data.results, function (item) {
return item[lookupKey] === value;
}));
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).select2('destroy');
});
},
update: function (element) {
$(element).trigger('change');
}
}
解决方法:
select2包装了一个表单字段,因此您不能直接发布JSON对象.如果可以的话,最简单的方法是修改服务器端代码以使用ID.
如果不是,则可以在select2构造函数中使用id参数,并返回在服务器上解析的字符串化JSON对象.例如(未测试)您的数据绑定:
select2: {
tags: ko.toJS($parent.availableProducts),
placeholder: 'select products',
id: function(product) { return JSON.stringify({server_id: product.id, server_text: product.text}) }
}
有关此方法的更多信息:
POST data in JSON format
https://github.com/ivaynberg/select2/issues/852#issuecomment-13478644
也许将来我们会有JSON form submission.
标签:jquery-select2,asp-net-mvc-4,knockout-js,javascript 来源: https://codeday.me/bug/20191120/2047911.html