Knockout TreeView Web Api绑定递归数组

时间:2014-12-08 12:20:04

标签: knockout.js asp.net-web-api

我有这样的树:

<script src="~/Scripts/tree.js"></script>

<script type="text/html" id="tree-node">
    <li>
        <span data-bind="text: Name"></span>

        <div>
            <ul data-bind="template: {name: 'tree-node', foreach: Children}"></ul>
        </div>
    </li>
</script>

<ul data-bind="template: {name: 'tree-node', foreach: tree}"></ul>

视图模型:

var ViewModel = function () {
var self = this;
self.tree = ko.observableArray([]);

self.getTree = function() {
    $.get('/api/tree', 'json', function(data) {
        self.tree(data);
    });
}.bind(self);

};

var vm = new ViewModel();
vm.getTree();
ko.applyBindings(vm);

API:

public List<Objects> Get()
{
    ctx.Configuration.LazyLoadingEnabled = false;
    ctx.Configuration.ProxyCreationEnabled = false;
    return ctx.Objects.ToList().Where(z=>z.Parent==null).ToList();
}

对象包含子项,必须绑定到树:

public class Objects
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public string Details { get; set; } 
    public virtual Objects Parent { get; set; }    
    public virtual ICollection<Objects> Children { get; set; }
}

最后我什么都没得到。 我在Knockoutjs上下文调试器中查看viewmodel,我看到了我的数据。但它没有在页面上呈现。为什么呢?

1 个答案:

答案 0 :(得分:2)

tree是一个数组,因此您应将其定义为:

self.tree = ko.observableArray([]);

问题来自父ul绑定:

<ul data-bind="template: {name: 'tree-node', data: tree}"></ul>

它只会使用data=tree ==&gt;呈现模板一次这会将模板上下文设置为tree数组,该数组没有NameChildren属性。这些属性属于此数组中的元素。所以你必须将绑定更改为:

<ul data-bind="template: {name: 'tree-node', foreach: tree}"></ul>