繁体   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