2012-03-23 75 views
1

當使用對象作爲選擇列表值時,我無法使用Knockout選擇列表綁定。如果我使用字符串,它工作正常,但我想綁定對象。Knockout.js選擇值綁定到對象

我有一個禮物對象,它有一個標題,價格和公司。我有一個公司名單,每家公司都有一個ID和名稱。然而,初始選擇在選擇列表中不正確。

請參閱小提琴:http://jsfiddle.net/mrfunnel/SaepM/

這種結合MVC3視圖模型時,對我很重要。雖然我承認這可能是因爲我以錯誤的方式做事。

如果我有以下型號:

public class Company 
{ 
    public Guid Id { get; set; } 
    public string Name { get; set; } 

} 
public class GiftModel 
{ 
    public Company Company { get; set; } 
    public string Title { get; set; } 
    public double Price { get; set; } 
} 

如何選擇一個公司,是在綁定我的控制器?我是否需要向GiftModel添加CompanyId屬性並綁定到該屬性或編寫自定義綁定器。我在這裏錯過了什麼?

在此先感謝。

回答

3

你需要做很多東西。

您的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">&nbsp;</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);​ 
+0

謝謝你花時間回答這個問題。我看到這是解決問題的唯一方法。你是冠軍。 – TheGwa 2012-05-07 10:35:13

0

使對象觀察到,使用foeach結合。如果你有這樣一個場景:

var model = { 
    myObj : ko.observable(); 
} 

,如果你嘗試綁定到myObj.label它不會工作:

<span><a href="#" data-bind="text: myObj.label"></a></span> 

然而,使用foreach綁定:

<span data-bind="foreach: myObj"><a href="#" data-bind="text: label"></a></span> 

ko以通常javascript方式通過數組的方式迭代屬性,事情就會起作用。