I am using @Helper ShowTree in my Project but I have problem with child items. In my view , child items displaying 2 times and look like parent menu. I looked samples in site, but not find difference. Where is my wrong ?
MyEntity
public class Kategori
{
public Kategori()
{
this.Children = new List<Kategori>();
}
public int ID { get; set; }
public string Name { get; set; }
public int ParentID { get; set; }
public virtual List<Kategori> Children { get; set; }
}
Controller
public ActionResult Index()
{
context = new CrudContext();
List<Kategori> kategoriler= context.Kategoriler.ToList();
return View(kategoriler);
}
I think my problem is in my View.
View
@model List<JQueryDataTableCrud.Models.Kategori>
@RecursiveMenu(Model)
<div>
@helper RecursiveMenu(List<JQueryDataTableCrud.Models.Kategori> kategoriler)
{
<ul>
@foreach (var item in kategoriler)
{
<li>
<span>@item.Name</span>
@if (item.Children.Any() && item.Children != null)
{
@RecursiveMenu(item.Children)
}
</li>
}
}
</ul>
}
</div>
Result
.Elektronik
-Cep Telefonu
-Mutfak
.Bilgisayar
.Cep Telefonu
.Mutfak
If you're storing all of your Kategori
in the same table, then you'll need a way to distinguish a parent from child in the initial query.
var kategoriler = context.Kategoriler.Where(k => k.ParentID == 0).ToList();
/*
.Elektronik
-Cep Telefonu
-Mutfak
.Bilgisayar
*/
That should restrict the top-level to the two parent items. This assumes you set ParentID = 0
; This also assumes your context populates the Children
.
Your recursive routine should be fine
@helper RecursiveMenu(List<JQueryDataTableCrud.Models.Kategori> kategoriler)
{
@foreach (var item in kategoriler)
{
<span>@item.Name</span>
@if (item.Children.Any() && item.Children != null)
{
@RecursiveMenu(item.Children)
}
}
}