在ajax
请求select
标记后,如果我绑定下拉列表,则不会读取value
属性。但是当我绑定view model
recognise
中的下拉列表时,例如:
如果我像这样绑定模型
,它就可以了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'
}
但是如果我在ajax请求之后绑定模型,则来自months数组的所有名称的来源都被绑定,但默认情况下所选项目在此示例中不起作用value of 3
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>
答案 0 :(得分:1)
在您的示例中,ajax调用将花费一些时间来执行(异步)。但是,绑定可能在调用完成之前应用。这导致以下结果:
试试这个:
$.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);
}));
self.selectedMonth(3);
}
});
<select data-bind="options: $root.months,
optionsText: 'Name',
optionsValue: 'ID',
value: $root.selectedMonth"></select>
如果可行,请尝试在月份加载后设置selectedMonth
。