Knockout和MVC Collection绑定

时间:2012-12-07 07:13:56

标签: asp.net-mvc model-view-controller knockout.js knockout-mvc

我试图在MVC中开始使用Knockout并设法使正常的绑定/映射工作,但是当涉及到集合时我会陷入困境。到目前为止,我有以下代码:

public class TestViewModel
{
    public TestViewModel()
    {
        Persons = new List<Person>();
    }

    public List<Person> Persons { get; set; } 

}

public class Person
{
    public Person()
    {
    }

    public string Name { get; set; }
    public string Surname { get; set; }
    public List<string> Children { get; set; } 
}

cshtml代码:

<h2>People</h2>
<div data-bind="template: { name: 'person-template', foreach: persons }"></div>

<script type="text/html" id="person-template">
    <ul>
        <li>
            <div><span data-bind="text: name"/>&nbsp;<span data-bind="text: surname"/> has <span data-bind='text: children().length'/></div>
            <ul data-bind="foreach: children">
                <li><span data-bind="text: $data"> </span></li>
            </ul>
        </li>
    </ul>
</script>

<script type="text/javascript">

var TestModel = function(model) {
    var self = this;
    self.persons = ko.observableArray(ko.utils.arrayMap(model.Persons, function(person) {
        var per = new Person(person);
        return per;
    }));
};

var Person = function(person) {
    var self = this;
    self.Name = ko.observable(person.Name);
    self.Surname = ko.observable(person.Surname);
    self.Children = ko.observableArray(person.Children);
};


$(function() {
        var data = @(Html.Raw(Json.Encode(Model)));
        ko.applyBindings(new TestModel(data));
    });

</script>

我遇到的问题是不确定映射是否完好,或者模板的输出是否有问题。

由于

1 个答案:

答案 0 :(得分:2)

问题是区分大小写的。这是正确的模板

<script type="text/html" id="person-template">
    <ul>
        <li>
            <div><span data-bind="text: Name"/>&nbsp;<span data-bind="text: Surname"/> has <span data-bind='text: Children().length'/></div>
            <ul data-bind="foreach: Children">
                <li><span data-bind="text: $data"> </span></li>
            </ul>
        </li>
    </ul>
</script>