2013-05-02 108 views
0

我在將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()); 

回答

1

value結合作爲一個參數的屬性的引用,而不是一個字符串(因此不是屬性名稱像optionsValueoptionsValue)。

所以,正確的用法是:

<select data-bind="options: $root.groupList, 
         optionsText: 'GroupName', 
         optionsValue: 'Id', 
         optionsCaption: 'No Group', 
         value: SelectedGroupId"></select> 

演示JSFiddle.