I have a partial view in an MVC 4 project, which is strongly typed. It takes an IEnumerable collection of a table of a database. In that table there are IDs, Names, and Pare
man, you got some wonk going on here. i feel your pain on getting stuck.
see if this floats your boat.
you need a seed value to keep track of what you are looking for in the listing when you do recursion on the same list. it's better to do a parent children mapping in the class, but meh this was fun to do given your structure and should do the trick.
Models
namespace trash.Models
{
public class Category
{
public int ID { get; set; }
public int? Parent_ID { get; set; }
public string Name {get; set;}
}
public class SeededCategories
{
public int? Seed { get; set; }
public IList<Category> Categories { get; set; }
}
}
Controller (NOTE: you start the recursion chain by setting the Seed property to null which will pick up all the null parents)
namespace trash.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
IList<trash.Models.Category> categories = new List<trash.Models.Category>();
categories.Add(new trash.Models.Category { ID = 1, Parent_ID = null, Name = "Top1" });
categories.Add(new trash.Models.Category { ID = 2, Parent_ID = null, Name = "Top2" });
categories.Add(new trash.Models.Category { ID = 3, Parent_ID = 1, Name = "Top1Ring1" });
categories.Add(new trash.Models.Category { ID = 4, Parent_ID = 1, Name = "Top1Ring2" });
trash.Models.SeededCategories model = new Models.SeededCategories { Seed = null, Categories = categories };
return View(model);
}
}
}
Views Index
@model trash.Models.SeededCategories
Here's a list
@Html.Partial("_TreeCategories", Model)
Partial (your _TreeCategories. NOTE: set the Seed to the current node ID and volia recursion)
@model trash.Models.SeededCategories
@if (Model.Categories.Where(s => s.Parent_ID == Model.Seed).Any())
{
<ul>
@foreach (var node in Model.Categories)
{
if (node.Parent_ID == Model.Seed)
{
trash.Models.SeededCategories inner = new trash.Models.SeededCategories { Seed = node.ID, Categories = Model.Categories };
<li><a href="?@node.ID">@node.Name</a>
@Html.Partial("_TreeCategories", inner)
</li>
}
}
</ul>
}
You can try Shield UI's recursive TreeView for ASP.NET MVC.
It allows you to specify all the TreeView items using a RecursiveDataSource object, which can be setup to retrieve the data for a tree item from a remote endpoint or a local source "lazily", whenever the item is being expanded.
The RecursiveDataSource is a wrapper around a JavaScript DS widget, which introduces the need for some JS code, as well as updating your server code that will provide the data (either implementing a web service, or place the data in a JS variable in your view).