Igor Levashov Igor Levashov - 5 months ago 32
jQuery Question

Binding options and optionsText in Select dropdown in knockout.js

I read everything here and different websites and don't understand my problem. Looks like it should work, but it doesn't. I am getting [Object object] as options.

Html

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


Knockout

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 Response

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

Answer

The value of optionsText is the string name of the property within each options array element to use for the text, so you should change your binding to:

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