简体   繁体   English

在Knockout中选择2选择标记作为对象而不是'id'

[英]Select2 selected tag as object instead of 'id' in Knockout

So i have a select2 tag input working fine, displaying the tags correctly, and storing the selected id into the selectedProducts observableArray. 所以我有一个select2标签输入工作正常,正确显示标签,并将选定的id存储到selectedProducts observableArray。 However, my HTTPPost is expecting an array of objects, and not an array of integers. 但是,我的HTTPPost期望一个对象数组,而不是一个整数数组。 I've been looking to see how I can have the select2 save as an object (ie {id: 1, text: "abc"}) instead of just an array of integers. 我一直在寻找如何将select2保存为对象(即{id:1,text:“abc”})而不仅仅是一个整数数组。

My binding is below: 我的约束如下:

<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 is wrapping a form field so you can't directly post a JSON object. select2正在包装表单字段,因此您无法直接发布JSON对象。 It may be easiest to modify the server side code to work with IDs if you can. 如果可以,最简单的方法是修改服务器端代码以使用ID。

If not you could use the id parameter in the select2 constructor, and return a stringified JSON object you parse on the server. 如果不是,您可以在select2构造函数中使用id参数,并返回您在服务器上解析的字符串化JSON对象。 For example (untested) in your data-bind : 例如, data-bind (未经测试):

select2: {
    tags: ko.toJS($parent.availableProducts),
    placeholder: 'select products',
    id: function(product) { return JSON.stringify({server_id: product.id, server_text: product.text}) }
}

More info on this approach: 有关此方法的更多信息:

POST data in JSON format https://github.com/ivaynberg/select2/issues/852#issuecomment-13478644 以JSON格式POST数据 https://github.com/ivaynberg/select2/issues/852#issuecomment-13478644

Maybe In the future we'll have JSON form submission . 也许将来我们会提交JSON表单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM