在knockout.js中选择下拉列表中的绑定选项和optionsText

时间:2016-07-05 04:31:07

标签: javascript jquery knockout.js

我在这里阅读了所有内容和不同的网站,并不理解我的问题。看起来应该可行,但事实并非如此。我将[Object object]作为选项。

HTML

 <select data-bind="options: Cities, optionsText: Cities.CityNameRu"></select>

敲除

function CityModel(data) {
    this.CityId = ko.observable(data.CityId);
    this.CityNameRu = ko.observable(data.CityNameRu);
    this.CityName = ko.observable(data.CityName);
}

function IndexModel() {
    var self = this;
    self.Cities = ko.observableArray([]);

    self.GetCities = function () {
        $.ajax({
            type: "GET",
            url: '/FetchCities',
            dataType: "json",
            success: function (data) {
                self.SuccessfullyRetrievedModelsFromAjax(data);   
            },
            error: function (err) {
                alert(err.status + " : " + err.statusText);
            }
        });
    };

    this.SuccessfullyRetrievedModelsFromAjax = function (models) {
        ko.utils.arrayForEach(models, function (model) {
            self.Cities.push(new CityModel(model));
        });
    };
    self.GetCities();
}

Json回复

[{"CityId":1,"CityName":"philadelphia","CityNameRu":"Филадельфия"},{"CityId":2,"CityName":"new-york","CityNameRu":"Нью Йорк"}

1 个答案:

答案 0 :(得分:2)

optionsText的值是每个options数组元素中用于文本的属性的字符串名称,因此您应该将绑定更改为:

<select data-bind="options: Cities, optionsText: 'CityNameRu'"></select>