Search code examples
c#kendo-uikendo-treeview

How to bind a Kendo treeview to a file directory


I would like to display a folder hierarchy as a Kendo treeview. I assume this involves converting the directory into JSON.

Is this possible and the right way to accomplish my goal or is there another way to bind the treeview to a remote file directory?


Solution

  • Since your tags are kendo-ui and C# I assume you are using Kendo UI for ASP.NET MVC. If not just change the view code with appropriate JS and the other code should work as expected in ASP.NET MVC.

    Create controller PathController with 2 actions: Read and Index.

    In your Index view call Kendo UI tree view helpers

    @(Html.Kendo().TreeView()
        .Name("PathTreeView")
        .DataTextField("Name")
        .DataSource(dataSource => dataSource
            .Read(read => read.Action("Read", "Path"))
        )
    )
    

    Create a view model KendoTreeViewViewModel for the kendo tree view:

    public class KendoTreeViewViewModel
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public bool HasChildren { get; set; }
    }
    

    In your Read action return JSON with files and folders:

    public JsonResult Read(string path)
    {
        const string StartDirectory = @"C:\";
        path = path ?? StartDirectory;
        var files = Directory.GetFiles(path).Select(file => 
            new KendoTreeViewViewModel
                {
                    Id = file,
                    HasChildren = false,
                    Name = Path.GetFileName(file)
                });
    
        var directories = Directory.GetDirectories(path).Select(dir =>
            new KendoTreeViewViewModel
                {
                    Id = dir,
                    HasChildren = true,
                    Name = Path.GetFileName(dir)
                });
    
        var result = files.ToList();
        result.AddRange(directories);
        result = result.OrderBy(x => x.HasChildren).ToList();
    
        return this.Json(result, JsonRequestBehavior.AllowGet);
    }