After making an ajax
request and binding the dropdown list, I noticed that the select
tag was not reading the value
attribute. However, when I bind the drop down list in the view model
, it does recognize the value. For example:
It works if I bind the model like this:
var CostModel = function (data) {
var getCosts = getAllCosts.bind(this);
getCosts();
var months = [{ ID: 1, Name: 'january' }, { ID: 2, Name: 'february' }, { ID: 3, Name: 'march' }, ];
this.months = ko.observableArray(months); //after this value is set by default with 'march'
}
However, when I bind the model after the ajax request, the source of all names from the months array is bound but the selected item by default doesn't work as expected. For instance, setting the value to 3 doesn't reflect correctly.
function getAllCosts() {
var self = this;
$.ajax({
url: "/CostManageView/List",
cache: false,
type: "GET",
contentType: 'application/json; charset=utf-8',
success: function (data) {
var months = [{ ID: 1, Name: 'january' }, { ID: 2, Name: 'february' }, { ID: 3, Name: 'march' }, ];
self.months(ko.utils.arrayMap(months, function (month) {
return new Month(month);
}));
}
});
}
HTML:
<select data-bind="options: $root.months,
optionsText: 'Name',
optionsValue: 'ID',
value: 3"></select>