Recursion in an ASP.NET MVC view

后端 未结 4 1070
后悔当初
后悔当初 2020-12-01 03:58

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

4条回答
  •  悲哀的现实
    2020-12-01 04:31

    You can reuse html parts with lambdas

    Example

    
    public class Category
        {
            public int id;
            public string name;
            public IEnumerable categories;
        }
    
     <%
            Action> categoriesMacros = null;
            categoriesMacros = categories => { %>
            
      <% foreach(var c in categories) { %>
    • <%= Html.Encode(c.name)%>
    • <% if (c.categories != null && c.categories.Count() > 0) categoriesMacros(c.categories); %> <% } %>
    <% }; %> <% var categpries = (IEnumerable)ViewData["categories"]; %> <% categoriesMacros(categpries); %>

提交回复
热议问题