using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication3 { public partial class WebForm1 : System.Web.UI.Page { Model1 db = new Model1(); public IEnumerable<Category> Categories { get; set; } protected void Page_Load(object sender, EventArgs e) { Categories = db.Category; } protected string RenderCategory(int parendId) { StringBuilder sb = new StringBuilder(); sb.Append("<ul>"); foreach (var item in Categories) { if (item.ParentId == parendId) { sb.AppendFormat("<li><a>{0}</a>", item.Name); sb.Append(RenderCategory(item.Id)); sb.Append("</li>"); } } sb.Append("</ul>"); return sb.ToString(); } } }
前端
<%=RenderCategory(0) %>
委托的方法
前端
<% int count = 0; RenderCategory = parentId => { %> <ul <%= parentId==0?"id=\"categories\" class=\"dropdown-menu\"":"class=\"sub-item\"" %>> <% foreach (var item in Categories) { if (item.ParentId == parentId) { // 有子类 %> <li> <a href="<%=UrlHelper.CategoryUrl(item.Id)%>"><%if (parentId == 0) {%><i class="icon-main icon-<%=count++ %>"></i><%}%><%= item.Name %></a> <% RenderCategory(item.Id); %> </li> <% } } %> </ul> <% }; %> <% RenderCategory(0); %>
后端比之前的方法 多了个 public Action<int> RenderCategory { get; set; } 属性
时间: 2024-11-03 17:36:45