1

我试图在 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>

我遇到的问题不确定映射是否完成或模板的输出是否存在问题。

谢谢

4

1 回答 1

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>
于 2012-12-07T07:41:47.267 回答