当前的应用设计风格趋于Flat扁平化,很多基于BootStrap实现了很多UI非常漂亮的管理界面(Bootstrap admin template)。首先看一下主界面:
查看左边导航的菜单html结构:
通过观察,可以发现其中菜单树的特点,这里注意一下,菜单顶级的标题显示在span中,另外class也不同。那边如何从数据库动态生成符合此特征的treemenu结构呢?
1 数据库字段设计
2 演示数据
5 菜单类实现:
首先树结构的菜单,自然想到用递归来构建,代码如下:
public class AdminLTEHelper { /// <summary> /// 根据DataTable生成AdminLTE的多级菜单目录 /// GetTreeJsonByTable(datatable, "id", "title", "pid", "0","menulevel"); /// </summary> /// <param name="tabel">数据源</param> /// <param name="idCol">ID列</param> /// <param name="txtCol">Text列</param> /// <param name="rela">关系字段(字典表中的树结构字段)</param> /// <param name="pId">父ID值(0)</param> /// <param name="colmenulevel">菜单显示层级列名</param> public StringBuilder result = new StringBuilder(); public StringBuilder sb = new StringBuilder(); public void GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string rela, object pId,string colmenulevel) { result.Append(sb.ToString()); sb.Clear(); if (tabel.Rows.Count > 0) { string filer = string.Format("{0}='{1}'", rela, pId); DataRow[] rows = tabel.Select(filer); if (rows.Length > 0) { foreach (DataRow row in rows) { if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0) { //第一层级,名称在<span>多级菜单</span>中 class为treeview //colmenulevel为menulevel,为菜单的显示层级,可以在后台进行配置 //和树的层级可能不同 if (row[colmenulevel].ToString() == "1") { sb.Append("<li class=\"treeview\"><a href=\"#\"><i class=\"fa fa-folder\"></i><span>" + row[txtCol] + "</span><span class=\"pull-right-container\"> <i class=\"fa fa-angle-left pull-right\"></i></span></a>"); } else { sb.Append("<li><a href=\"#\"><i class=\"fa fa-folder\"></i>" + row[txtCol] + "<span class=\"pull-right-container\"> <i class=\"fa fa-angle-left pull-right\"></i></span></a>"); } sb.Append("<ul class=\"treeview-menu\">"); GetTreeJsonByTable(tabel, idCol, txtCol, rela, row[idCol], colmenulevel); sb.Append("</ul>"); sb.Append("</li>"); result.Append(sb.ToString()); sb.Clear(); } else { //isleaf=true if (row[colmenulevel].ToString() == "1") { //顶级菜单,标题显示在span中,否则显示图标时,标题不能隐藏 sb.Append("<li class=\"treeview\"><a href=\"#\" moid=\"" + row[idCol] + "\",text=\"" + row[txtCol] + "\",isleaf=\"true\"" + ",url=\"" + row["url"] + "\"><i class=\"fa fa-folder\"></i><span>" + row[txtCol] + "</span></a></li>"); } else { sb.Append("<li><a href=\"#\" moid=\"" + row[idCol] + "\",text=\"" + row[txtCol] + "\",isleaf=\"true\"" + ",url=\"" + row["url"] + "\"><i class=\"fa fa-folder\"></i>" + row[txtCol] + "</a></li>"); } //sb.Append("<li><a href=\"#\" moid=\"" + row[idCol] + "\",text=\"" + row[txtCol] + "\",isleaf=\"true\"" + ",url=\"" + row["url"] + "\"><i class=\"fa fa-folder\"></i>" + row[txtCol] + "</a></li>"); result.Append(sb.ToString()); sb.Clear(); } result.Append(sb.ToString()); sb.Clear(); } } result.Append(sb.ToString()); sb.Clear(); } } }
6 调用
7 测试
验证生成的菜单结构是否正确,首先看看显示的层级结构和数据库是否一致,另外查看单击上级,是否可以展开,最后注意的是,在左边菜单收缩后,只显示图标,鼠标移动到图标上后,并能正确显示子菜单:
声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。