ASP.NET MVC 4 generating a treeview with recursive partial view

后端 未结 2 717
予麋鹿
予麋鹿 2020-12-13 22:10

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

2条回答
  •  既然无缘
    2020-12-13 22:58

    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 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 categories = new List();
                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())
    {
        
      @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 };
    • @node.Name @Html.Partial("_TreeCategories", inner)
    • } }
    }

提交回复
热议问题