using App.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Text; namespace App.Web.Controllers { public class HomeController : Controller { AppDBContainer db = new AppDBContainer(); public ActionResult Index() { IQueryable<SysModule> menus = db.SysModule.AsQueryable().Where(a=>a.ParentID=="0"); StringBuilder sb = new StringBuilder(); bool firstFlag = true;//第一个默认展开 GetChildMenus(ref sb, menus, firstFlag);//二级菜单 ViewBag.Menus = sb.ToString(); return View(); } //递归调用 public void GetChildMenus(ref StringBuilder sb, IQueryable<SysModule> menus,bool firstFlag)//二级以上菜单 { int count = 0; if(!firstFlag) sb.Append("<ul>"); foreach (var m in menus) { IQueryable<SysModule> menusChild = db.SysModule.AsQueryable().Where(a => a.ParentID == m.ID); count = menusChild.Count(); sb.AppendFormat("<li>",firstFlag?"start actove open":""); sb.AppendFormat("<a href='https://www.jb51.net/article/{0}'><i></i><span>{2}</span>{3}</a>", count > 0 ? "javascript:;" : m.Url, m.Iconic, m.Name, count > 0 ? "<span></span>" : ""); firstFlag = false; if (count > 0) GetChildMenus(ref sb, menusChild,firstFlag); sb.Append("</li>"); } if (!firstFlag) sb.Append("</ul>"); } } }
去掉提取的li替换成@Html.Raw(ViewBag.Menus)
6.总结
前端这种东西最考验人的耐心,不信你自己拼接一下
最后效果