I have two classes Category and Product and I want to expend products when users click a category node on the treeview.
My View is as follows:
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<div class="row">
<div class="col-md-3">
<label class="k-label-top">TreeView</label>
@(Html.Kendo().TreeView().Name("treeview")
.DataSource(datasource => datasource
.Read(read => read.Action("Categories", "Categories"))
).DataTextField("Name")
)
</div>
</div>
Controller
public ActionResult Categories(int? id)
{
var model = db.Categories
.Where(p => p.Id == id.Value || p.Id == null)
.Select(p => new {
id = p.Id,
Name = p.Name,
hasChildren = p.Products.Any()
});
return this.Json(model, JsonRequestBehavior.AllowGet);
}
Categories Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EmployeeTreeView.Models
{
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
}
Products Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EmployeeTreeView.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Category Category { get; set; }
public int CategoryId { get; set; }
}
}
When I remove the where clause in the controller the parent node just loops over and over again, but no child nodes are displayed.