Search code examples
asp.net-mvcasp.net-mvc-4treeviewkendo-ui

MVC with Kendo treeview - remote data JSON or XML


I'm trying to create a Kendo TreeView that gets populated from my controller (PropertyController).

The part I'm stuck at is how to format my data in the controller. How could I create a TreeView three items deep and pass that to my view to be displayed in the TreeView?

@(Html.Kendo().TreeView()
    .Name("treeview")
    .Events(events => events
        .DragStart("PartnershipPage.OnDragStart")
        .Drop("PartnershipPage.OnDrop")
        .DragEnd("PartnershipPage.OnDragEnd")
    )
    .HighlightPath(true)
    .DragAndDrop(true)
    .DataSource(dataSource => dataSource
        .Read(read => read
            .Action("Index","Tree")
        )
    )
)

I've included the controller to see if I'm doing it correctly. All that is happening so far is the JSON is being displayed on the screen as text.

Controller:

public ActionResult Index()
{
    var org = new Entities();
    var eList = new List<Entity>();

    var entity1 = new Entity
    {
        Id = 1,
        Name = "LLC-A",
        parentId = 0
    };
    eList.Add(entity1);

    var entity2 = new Entity
    {
        Id = 2,
        Name = "LLC-B",
        parentId = 0
    };
    eList.Add(entity2);

    var entity3 = new Entity
    {
        Id = 1,
        Name = "LLC-C",
        parentId = 2
    };
    eList.Add(entity3);

    var entity4 = new Entity
    {
        Id = 1,
        Name = "LLC-D",
        parentId = 2
    };
    eList.Add(entity4);

    org.Entity = eList;

    var test = from x in org.Entity
               where (x.Name != null)
               select new
               {
                   Id = x.Id,
                   Name = x.Name,
                   parentId = x.parentId
               };
    ;

    return Json(test, JsonRequestBehavior.AllowGet);
}

Solution

  • From: Kendo Site

    <%= Html.Kendo().TreeView()
        .Name("TreeView")
        .BindTo(Model, mapping => mapping
            .For<Customer>(binding => binding
                // The "child" items will be bound to the the "Orders" property
                .Children(c => c.Orders)
                // Map "Customer" properties to TreeViewItem properties
                .ItemDataBound((item, c) => item.Text = c.ContactName)
            )
            .For<Order>(binding => binding
                // "Orders" do not have child objects so return "null"
                .Children(o => null)
                // Map "Order" properties to TreeViewItem properties
                .ItemDataBound((item, o) => item.Text = o.OrderID.ToString())
            )
        )
    %>