Knockout Kendo dropdownlist get text of selected i

2019-07-12 02:14发布

问题:

My application is MVC 5. I am using the following Knockout Kendo dropdownlist:

     <input data-bind="kendoDropDownList: { dataTextField: 'name',
 dataValueField: 'id', data: foodgroups, value: foodgroup }" />
         <hr />
         Selected: <strong data-bind="text: foodgroup"> </strong>

    <script>
        var ViewModel = function () {
            var self = this;
            this.foodgroups = ko.observableArray([
                { id: "1", name: "apple" },
                { id: "2", name: "orange" },
                { id: "3", name: "banana" }
            ]);
            var foodgroup =
            {
                name: self.name,
                id: self.id
            };
            this.foodgroup = ko.observable();
            ko.bindingHandlers.kendoDropDownList.options.optionLabel = " - Select -";
            this.foodgroup.subscribe(function (newValue) {
                alert(newValue.name);
            });
        };
        ko.applyBindings(new ViewModel());
    </script>

I am trying to get the text of the selected item. If I use alert(newValue) I get the id, when I use newValue.name or newValue.Text I get undefined.

回答1:

I think that KendoDropDownList() does not support having a complex object as a data value. Then I think the better approach is using ko.utils.arrayFirst().

For convinience I did an Jsfiddle example

Hope This help