如何最初根据其数据源的字段检查 kendo 树视图中的复选框

How to check the checkbox in kendo treeview initially based on a field of it's datasource

当我编辑我的 kendo 树视图时,我需要显示一些已选中的节点和其他未选中的节点,所以我想根据数据源字段设置复选框的状态(称为:"IsSelected") 这是我的代码:

{    
    <div id="treeview"></div>
}

<script type="text/javascript">


    $(function () {
        var dataSource = new kendo.data.HierarchicalDataSource({
            transport: {
                read: {
                    url: "@Url.Action("GetItems", "myController")",
                    dataType: "json",
                    contentType: 'application/json; charset=utf-8',
                    traditional: true,
                    type: 'GET'
                }
            },
            schema: {
                model: {
                    id: "OrganizationChartId",
                    hasChildren: "HasChildren",
                    checked: "IsSelected"
                }
            }
        });

        $("#treeview").kendoTreeView({
            template: kendo.template($("#treeview-template").html()),
            checkboxes: {
                checkChildren: false
            },
            dataSource: dataSource,
            dataTextField: "OrganizationChartDesc",
            select: function (e) { console.log("Selecting: " + this.text(e.node)); },
            check: function (e) { console.log("Checkbox changed :: " + this.text(e.node)); },
            change: function (e) { console.log("Selection changed"); },
            collapse: function (e) { console.log("Collapsing " + this.text(e.node)); },
            expand: function (e) { console.log("Expanding " + this.text(e.node)); }
        });
    });
</script>

但不幸的是它不起作用,选中:"IsSelected" 选中所有节点。请指导我解决这个问题。

我建议您使用与以下代码相同的解决方案:

在您的视图文件中:

@using Kendo.Mvc.UI

<div class="k-rtl">

 @(Html.Kendo().TreeView()
 .Name("treeview")
 .BindTo((IEnumerable<TreeViewItemModel>)ViewBag.kendoTreeViewDataSource)
 .ExpandAll(false).LoadOnDemand(false)
 .Events(c => c.Change("TreeViewNodeSelected"))
 .
 .
 .
)

</div>

并且在控制器的操作方法中,您应该像这样设置 "ViewBag.kendoTreeViewDataSource" :

public ActionResult IndexView()
{
  ViewBag.kendoTreeViewDataSource = GetDataSource();
  return View();
}

private IEnumerable<TreeViewItemModel> GetDataSource()
{
    var result = new List<TreeViewItemModel>();

    var yourDataList = .... //for exapmle select data from Database and put into a List of your class

   //you should convert your data into result
   // you can use linq query for mapping 
   result =   yourDataList.select(c=>new TreeViewItemModel{
        Id = c.OrganizationChartId ,
        Text = c.OrganizationChartDesc,
        Items = ... // this is for child node , you can use a recursive function for getting child value from your DataList

        Checked = IsSelected , // true for checked checkbox and false for unchecked
   }).ToList();    
}