你需要做很多東西。
您的ViewModel中的CompanyId是綁定並使其成爲可觀察對象的唯一方法。 你不能讓一個觀察的對象只it's值
<form class="giftListEditor" data-bind="submit: save">
<!-- Our other UI elements, including the table and ‘add’ button, go here -->
<p>You have asked for <span data-bind="text: gifts().length"> </span> gift(s)</p>
<table>
<tbody data-bind="foreach: gifts">
<tr>
<td>Gift name: <input data-bind="value: Title"/></td>
<td>Price: $ <input data-bind="value: Price"/></td>
<td>Company: <select data-bind="options: $root.companies, optionsText: 'Name', optionsValue: 'Id', value: CompanyId"/></td>
<td>CompanyId: <span data-bind="text: CompanyId"></span></td>
<td><a href="#" data-bind="click: $root.removeGift">Delete</a></td>
</tr>
</tbody>
</table>
<button data-bind="click: addGift">Add Gift</button>
<button data-bind="enable: gifts().length > 0" type="submit">Submit</button>
</form>
模型
// Fake data
var initialData = [
{ Title: ko.observable('Item 1'), Price: ko.observable(56), CompanyId: ko.observable(1) },
{ Title: ko.observable('Item 2'), Price: ko.observable(60), CompanyId: ko.observable(2) },
{ Title: ko.observable('Item 3'), Price: ko.observable(70), CompanyId: ko.observable(2) }
];
var initialCompanies = [
{ Id: 1, Name: "Comp 1" },
{ Id: 2, Name: "Comp 2" },
{ Id: 3, Name: "Comp 3" }
];
var viewModel = {
gifts: ko.observableArray(initialData),
companies: initialCompanies,
addGift: function() {
this.gifts.push({
Title: "",
Price: "",
Company: { Id: "", Name: "" }
});
},
removeGift: function($gift) {
viewModel.gifts.remove($gift);
},
save: function() {
console.log(ko.toJS(viewModel.gifts));
}
};
ko.applyBindings(viewModel, document.body);
謝謝你花時間回答這個問題。我看到這是解決問題的唯一方法。你是冠軍。 – TheGwa 2012-05-07 10:35:13