You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MVC.Net中编写实现无限层级分类树的Foreach循环?

Got it, your current code only handles two levels of categories (top-level and their direct children), which is why it can’t build an infinite-depth category tree. The fix here is to use recursion—since your Categories class already has a self-referential collection (Categories1 for child categories), we can leverage that to render nested levels repeatedly.

Here’s a practical, step-by-step solution:

1. Create a Recursive Partial View

First, make a partial view (let’s name it _CategoryTree.cshtml) that will handle rendering a category and all its nested children. This view will call itself for each level of subcategories:

@model IEnumerable<Categories>

@if (Model != null && Model.Any())
{
    <ul class="nested-categories">
        @foreach (var category in Model)
        {
            <li>
                <!-- Render current category name -->
                <span>@Html.DisplayFor(modelItem => category.CategoryName)</span>
                <!-- Recursively render this category's child categories -->
                @await Html.PartialAsync("_CategoryTree", category.Categories1)
            </li>
        }
    </ul>
}

2. Update Your Main Razor View

Modify your main view to render only top-level categories, then trigger the recursive partial view to handle their nested children:

@foreach (var mainCategory in Model.Where(a => a.parentCategoryId == null))
{
    <div class="category-panel">
        <h5 class="panel-title">@Html.DisplayFor(modelItem => mainCategory.CategoryName)</h5>
        <!-- Call the partial view to render all child levels for this top category -->
        @await Html.PartialAsync("_CategoryTree", mainCategory.Categories1)
    </div>
}

3. Optional: Adapt for Table Layout (Matching Your Original Code)

If you need to keep the table structure from your initial code, adjust the partial view to fit table rows and add indentation for visual hierarchy:

@model IEnumerable<Categories>

@if (Model != null && Model.Any())
{
    @foreach (var category in Model)
    {
        <tr>
            <td style="padding-left: 25px;">@Html.DisplayFor(modelItem => category.CategoryName)</td>
            <td>@Html.DisplayFor(modelItem => category.Categories2?.CategoryName)</td>
        </tr>
        <!-- Recursively render child categories with increased indentation -->
        @await Html.PartialAsync("_CategoryTree", category.Categories1)
    }
}

Key Performance Tip

To avoid slow N+1 database queries, make sure you preload nested categories when fetching your model data. If you’re using Entity Framework, use Include to eager-load the child collections:

var categories = db.Categories
                   .Include(c => c.Categories1) // Load direct child categories
                   .ThenInclude(c => c.Categories1) // Optional: Load grandchild categories for deeper levels
                   .ToList();

This ensures all nested category data is fetched in a single query instead of hitting the database every time the partial view renders a new level.

内容的提问来源于stack exchange,提问作者Emre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:05:50