簡體   English   中英

Knockout.js選擇將值綁定到對象

[英]Knockout.js Select value binding to object

將對象用作選擇列表值時,無法使用Knockout選擇列表綁定。 如果我使用字符串,但我想綁定對象,則效果很好。

我有一個禮物對象,並且它具有標題,價格和公司。 我有一個選擇的公司列表,每個公司都有一個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; }
}

如何選擇在控制器中具有約束力的公司? 我需要將CompanyId屬性添加到GiftModel並綁定到該屬性還是編寫自定義活頁夾。 我在這里缺少基本的東西嗎?

提前致謝。

您需要做很多事情。

ViewModel中的CompanyId是綁定並使之可觀察的唯一方法。 您不能僅使對象的值成為可觀察的對象

<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);​

要使對象可觀察,請使用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方式遍歷數組一樣遍歷屬性,一切都會正常進行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM