I have a nested data object for a set of items within categories. Each category can contain sub categories and there is no set limit to the depth of sub categories. (A file system would have a similar structure.) It looks something like this:
class category
{
public int id;
public string name;
public IQueryable<category> categories;
public IQueryable<item> items;
}
class item
{
public int id;
public string name;
}
I am passing a list of categories to my view as IQueryable<category>
. I want to output the categories as a set of nested unordered list (<ul>
) blocks. I could nest foreach loops, but then the depth of sub categories would be limited by the number of nested foreach blocks. In WinForms, I have done similar processing using recursion to populate a TreeView
, but I haven't seen any examples of using recursion within an ASPX MVC view.
Can recursion be done within an ASPX view? Are there other view engines that include recursion for view output?
You can use helper methods.
More info can be found on this link: http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx
Create your own HtmlHelper extension method like so:
Funny you should ask because I actually created one of these just yesterday.
You could easily do it by having each
<ul>
list in aPartialView
, and for each new list you need to start you just callHtml.RenderPartial("myPartialName");
.So the
Category
PartialView could look like this:In your View, you simply send the "root" collection as the model for the partial view:
EDIT:
Html.RenderPartial()
call - of course the category has to be passed as the model.You can reuse html parts with lambdas
Example