Knockout.js选择绑定到对象的值

The*_*Gwa 1 javascript binding select asp.net-mvc-3 knockout.js

当使用对象作为选择列表值时,我没有使用Knockout选择列表绑定.如果我使用字符串,它工作正常,但我想绑定对象.

我有一个Gift对象,它有标题,价格和公司.我有一个公司的选择列表,每个公司都有一个Id和Name.但是,初始选择在选择列表中不正确.

请看小提琴: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; }
}
Run Code Online (Sandbox Code Playgroud)

如何选择可在我的控制器中绑定的公司?我是否需要将一个CompanyId属性添加到GiftModel并绑定到该属性或编写自定义绑定器.我错过了一些基本的东西吗?

提前致谢.

小智 5

你需要做很多事情.

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>?
Run Code Online (Sandbox Code Playgroud)

你的模特

// 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);?
Run Code Online (Sandbox Code Playgroud)