ASP.NET MVC递归遍历菜单
效果图:
SiteNavService
namespace DotNetMVC.Service
{
public partial class SiteNavService : BaseService<SiteNav>, ISiteNavService
{
private IQueryable<SiteNav> GetJoinAll()
{
return GetAll()
.Include(u => u.FunctionalModule)
.AsNoTracking();
}
/// <summary>
/// 获取菜单数据
/// </summary>
/// <returns></returns>
public SiteNavDTO[] GetSiteNavs()
{
return GetJoinAll().OrderBy(e=>e.Sort).ThenBy(e=>e.Id).ToList().Select(p => ToDTO(p)).ToArray();
}
#region 递归获取菜单
/// <summary>
/// 递归获取菜单
/// </summary>
/// <param name="navLevel">菜单级数, 不指定,默认返回全部</param>
/// <returns></returns>
public List<SiteNavDTO> GetSiteNavsByLevel(int navLevel = 0)
{
SiteNavDTO[] allSiteNav = GetSiteNavs();
return GetGetSiteNavs(allSiteNav, 0, navLevel);
}
/// <summary>
/// 递归获取菜单
/// </summary>
/// <param name="allSiteNav"></param>
/// <param name="parentId"></param>
/// <param name="navLevel"></param>
/// <returns></returns>
private List<SiteNavDTO> GetGetSiteNavs(SiteNavDTO[] allSiteNav, long parentId, int navLevel)
{
List<SiteNavDTO> list = new List<SiteNavDTO>();
//默认获取全部菜单
IEnumerable<SiteNavDTO> childSiteNavs = allSiteNav.Where(e => e.ParentId == parentId);
if (navLevel != 0)
{
//获取指定级数菜单
childSiteNavs = childSiteNavs.Where(e => e.NavLevel <= navLevel);
}
//没有子菜单
if (childSiteNavs.Count() <= 0)
{
return list;
}
foreach (SiteNavDTO dto in childSiteNavs)
{
list.Add(dto);
//递归获取子菜单
list.AddRange(GetGetSiteNavs(allSiteNav, dto.Id, navLevel));
}
return list;
}
#endregion
private SiteNavDTO ToDTO(SiteNav entity)
{
SiteNavDTO dto = new SiteNavDTO();
dto.CreateDateTime = entity.CreateDateTime;
dto.Id = entity.Id;
dto.FunctionalModuleId = entity.FunctionalModuleId;
dto.ParentId = entity.ParentId;
dto.NavLevel = entity.NavLevel;
dto.NavName = entity.NavName;
dto.NavTarget = entity.NavTarget;
dto.NavUrl = entity.NavUrl;
dto.NavImg = entity.NavImg;
dto.ViewHtmlTemplate = entity.ViewHtmlTemplate;
dto.ListHtmlTemplate = entity.ListHtmlTemplate;
dto.Sort = entity.Sort;
dto.IsShow = entity.IsShow;
dto.IsEnabled = entity.IsEnabled;
dto.Remark = entity.Remark;
dto.FunName = entity.FunctionalModule.FunName;
return dto;
}
}
}
SiteNavController
SiteNavAddGetViewModel model = new SiteNavAddGetViewModel();
List<SelectListItem> listSiteNav = new List<SelectListItem>();
listSiteNav.Add(new SelectListItem { Value = "0", Text="一级菜单" });
foreach (SiteNavDTO dto in siteNavService.GetSiteNavsByLevel())
{
SelectListItem listItem = new SelectListItem();
for (int i = 0; i < dto.NavLevel; i++)
{
dto.NavName = "|-" + dto.NavName;
}
listItem.Text = dto.NavName;
listItem.Value = dto.Id.ToString();
listItem.Selected = false;
listSiteNav.Add(listItem);
}
model.ListSiteNav = listSiteNav;
View
<span class="select-box" style="width:150px;">
@Html.DropDownList("parentNav", Model.ListSiteNav, new { @class = "select" })
</span>