根据“ParentId”字段指定Kendo树视图子项

时间:2013-06-12 11:33:55

标签: javascript json kendo-ui

我有一个记录列表,我将其转换为 json

[ { "id": 1, "name": "A", "parentID": 0, "hasItems": "true" },
  { "id": 2, "name": "B", "parentID": 1, "hasItems": "false" },
  { "id": 3, "name": "C",  "parentID": 1, "hasItems": "false" },
  { "id": 4, "name": "D",  "parentID": 0, "hasItems": "false" }
]

现在我希望从json 数据上面创建一个KendoTreeView:

<div id="treeview55"></div>

<script>
    dtSrc = new kendo.data.HierarchicalDataSource({
    transport: {
        read: {
            url: "http://localhost:1132/Discontent/GetTreeNodes",
            dataType: "json"
        }
    },
        ,
    schema:{
        model: {
            id: 'id',
            parentId: 'parentID',
            name: 'name'
        }
    }
});

$("#treeview55").kendoTreeView({
    dataSource: dtSrc,
    dataTextField: "name",
    dataValueField: 'id',
});

结果:

    A
    B
    C
    D

我的预期结果:

   > A
         B
         C
     D

我的问题:

有没有办法用上面的json数据创建一个具有上述预期结果的KendoTreeView(级联子节点和父节点)???

2 个答案:

答案 0 :(得分:1)

请参阅下面的部分代码将帮助您解决问题

     <div id="tree"></div>
   <script>
        var flatData = [ { "id": 1, "text": "A", "parent": 0, "hasItems":                "true" },
 { "id": 2, "text": "B", "parent": 1, "hasItems": "false" },
    { "id": 3, "text": "C",  "parent": 1, "hasItems": "false" },
   { "id": 4, "text": "D",  "parent": 0, "hasItems": "false" }
  ];

  function processTable(data, idField, foreignKey, rootLevel) {
  var hash = {};

 for (var i = 0; i < data.length; i++) {
var item = data[i];
var id = item[idField];
var parentId = item[foreignKey];

hash[id] = hash[id] || [];
hash[parentId] = hash[parentId] || [];

     item.items = hash[id];
    hash[parentId].push(item);
    }

   return hash[rootLevel];
 }

 // the tree for visualizing data
  $("#tree").kendoTreeView({
 dataSource: processTable(flatData, "id", "parent", 0),
     loadOnDemand: false
   });
  </script>

我只是根据您的样本数据准备样本,我希望它对您有所帮助。

Find answer from this jsbin

答案 1 :(得分:0)

此刻,没有。 Kendo UI TreeView使用分层数据,上面是一个扁平化的层次结构。您需要处理数据以使其变为分层数据,如此excellent answer by Jon Skeet所示。

相关问题