我有一个奇怪的情况,将我的视图模型绑定到选择列表显示正确的行数,但显示的数据是空的;正确数量的选项元素,但每个都有一个空值和文本。下面的模型是正确的;选择一个值可以正常工作,保存后,我的视图模型代码会保存正确的值。只是什么都看不见。使用函数绑定虽然有效;例如,这显示正确:
<select data-bind="options: promotionLevels,
optionsText: function(item) {
return item().description();
},
optionsValue: function(item) {
return item().id();
},
value: promotionLevel,
optionsCaption: 'Choose...'"></select>
虽然这不是:
<select data-bind="options: promotionLevels,
optionsText: 'description',
optionsValue: 'id',
value: promotionLevel,
optionsCaption: 'Choose...'"></select>
我对淘汰赛比较陌生,很想知道问题是什么。
谢谢
[编辑]服务器生成的数据是:
"promotionLevels":[{"id":"f28391a0-8995-45a4-a360-1dd1ae38861b","description":"Beta"},{"id":"6fb6ad46-fff4-4da8-98ef-4ff469406a6c","description":"Development"},{"id":"f16d044a-4ea6-4001-844e-c8dad6227c04","description":"Production"},{"id":"1da6ac1f-7d31-ba64-fbce-c8623af6464f","description":"QA"},{"id":"bc34a34a-0c89-4215-a001-1ea40433b8a9","description":"Test"}]
转储数据,一旦通过ko绑定,提升等级为:
"promotionLevels": [
{
"id": "f28391a0-8995-45a4-a360-1dd1ae38861b",
"description": "Beta",
"__ko_mapping__": {
"ignore": [],
"include": [
"_destroy"
],
"copy": [],
"mappedProperties": {
"id": true,
"description": true
}
}
},
{
"id": "6fb6ad46-fff4-4da8-98ef-4ff469406a6c",
"description": "Development",
...
我试过 jsfiddle 这个,但依赖关系太大了。
[编辑 2]
页面代码为:
var mapping = {
promotionLevel: {
create: function(ctx) {
return ko.observable(new Foo.ReferenceDataModel(ctx));
}
},
...
};
var viewModel = @Html.Knockout().ToViewModel(this.Model, @<text>mapping</text>);
ko.applyBindings(viewModel, $("#endpointEditor")[0]);
以及视图模型代码:
Foo.ReferenceDataModel = $.inherit(
Foo.ViewModelBase,
{
__constructor: function(options) {
this.__base();
if (options && options.data) {
ko.mapping.fromJS(options.data, options.mapping || { }, this);
} else {
this.id = ko.observable($.generateId());
this.description = ko.observable();
}
this.save = function(data, e) {
var self = this;
var form = $(e.target).parents("form");
$.validator.unobtrusive.parse(form);
if (!$(form).valid()) {
return;
}
if (options.callback) {
options.callback(self);
}
};
}
});
这是我继承的一个应用程序,有一组复杂的模型等。基本视图模型只是添加了默认的错误处理。