I want to make a tree structured product category view. I have found this article by Ole Michelsen from 2011, which I think looks promising. The article describes a method similar to what I almost had in mind, using Razor to recursively render the tree structure.
My database table is almost identical to the one described in the article:
[ProductCategory]
Id
ParentId
Title
I'm not sure what my view model should look like. Should it be an IEnumerable of ProductCategory, or should it be an instance of ProductCategory and have an IEnumerable of ProductCategories in it?
Something like this ...
public class ViewModelProductCategory
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string Title { get; set; }
public int SortOrder { get; set; }
public int NumOfProducts { get; set; }
}
... or more like this?
public class ViewModelProductCategory
{
public IEnumerable<ProductCategory> ProductCategory { get; set; }
//public int NumOfProducts { get; set; }//<--Not too sure about this property
public IEnumerable<Product> Products { get; set; }
}
If the second one is closer to the "correct" one, how can I have SortOrder and NumOfProducts (how many products are in the current category)?
And the thing I'm most confused about, is how the razor rendering comes together. How do I send the viewmodel to the recursive partial view, and how does the partial view know which item to render?
I have some razor-code, but I can guarantee that posting it will NOT make anything clearer as of what I'm trying to achieve.
This pseudo-code is perhaps more describing:
_recursivePartial.cshtml
@model [my unknown viewmodel goes here, is it IEnumerable or not?]
<ul>
foreach item in model
{
<li>@Html.Partial("_recursivePartial.cshtml", [what goes here?])
// 1: How does _recursivePartial.cshtml know where in the tree it is?
// 2: How does this structure relate to the data structure in the DB?
}
</ul>