在Knockout select中设置初始值
问题描述:
我在将select的初始值等于我的挖空模型中的值时遇到了问题。在Knockout select中设置初始值
http://jsfiddle.net/npearson99/bjwAT/2/
在这种小提琴,集团应该是“组2”,但它不选择任何组。
如果我将value: 'SelectedGroupId'
更改为value: 2
,它可以工作。
<div data-bind="with: selectedWorkout">
<h3>Current Workout</h3>
Workout Id:
<label data-bind="text: Id"></label>
<br/>Workout Name:
<label data-bind="text: Name"></label>
<br/>Group:
<select data-bind="options: $root.groupList,
optionsText: 'GroupName',
optionsValue: 'Id',
optionsCaption: 'No Group',
value: 'SelectedGroupId'"></select>
function Group(Id, GroupName) {
var self = this;
self.Id = Id;
self.GroupName = GroupName;
}
function Workout(id, name, selectedGroupId) {
var self = this;
self.Id = id;
self.Name = name
self.SelectedGroupId = ko.observable(selectedGroupId);
}
function viewModel() {
var self = this;
self.groupList = ko.observableArray([
new Group(1, 'Group One'),
new Group(2, 'Group Two'),
new Group(3, 'Group Three')]);
self.selectedWorkout = ko.observable(new Workout(4, 'Test Workout', 2));
}
ko.applyBindings(new viewModel());
答
的value
结合作为一个参数的属性的引用,而不是一个字符串(因此不是属性名称像optionsValue
或optionsValue
)。
所以,正确的用法是:
<select data-bind="options: $root.groupList,
optionsText: 'GroupName',
optionsValue: 'Id',
optionsCaption: 'No Group',
value: SelectedGroupId"></select>