Emre
Emre

Reputation: 184

How to code a Foreach Loop for Endless Categories Tree in MVC.Net?

Categories Table:

 CategoryId (int) PK 
 ParentCategoryId (int) FK
 CategoryName

public class Categories
{
    public Categories() 
    { 
        this.Categories1 = new HashSet<Categories>(); 
        this.Products = new HashSet<Products>(); 
    } 

    public short CategoryId { get; set; } 
    public Nullable<short> parentCategoryId { get; set; } 
    public string CategoryName { get; set; } 

    public virtual ICollection<Categories> Categories1 { get; set; } 
    public virtual Categories Categories2 { get; set; } 
    public virtual ICollection<Products> Products { get; set; }
}

ParentCategoryId is for navigating the categories, and if ParentCategoryId is NULL in a category row, it means that Category is a main Category.

What I have so far:

 @foreach (var mainCategory in Model.Where(a => a.parentCategoryId == null))
 {
    <div ...something >
        <h5 class="panel-title">@Html.DisplayFor(modelItem => mainCategory.CategoryName)</h5>

            @foreach (var childCategory in Model.Where(b => b.parentCategoryId == mainCategory.CategoryId))
            {
                if (childCategory.parentCategoryId != null)
                {
                    <tr>
                        <td>@Html.DisplayFor(modelItemSub => childCategory.CategoryName)</td>
                        <td>@Html.DisplayFor(modelItemSub => mainCategory.CategoryName)</td>
                    </tr>
                }
            }
         }

... and of course it doesn't make a categories tree.

Upvotes: 2

Views: 494

Answers (1)

mnieto
mnieto

Reputation: 3874

Here is an aproximation with a recursive solution:

In your view:

@WriteChilds(null, "")

And this the method body, I'm sure you can translate Console.WriteLine to html output:

public void WriteChilds(int? ParentCategoryId, string parentName) {
    var categories = Model.Where(a => a.parentCategoryId == ParentCategoryId);
    foreach(var category in categories) {
        Console.WriteLine(parentName + " " + category.CategoryName);
        WriteChilds(category.CategoryId, category.CategoryName);
    }
}

Upvotes: 2

Related Questions