First project using EPiServer 7 with MVC4
Couldn't find much information regarding an two leveled top menu so I created this one,
please feel free to give feedback. It feels that this can be made easier.
This code resides in an partial view called TopNav.cshtml
@using EPiServer
@using EPiServer.Core
@using EPiServer.Filters
@using EPiServer.Web.Mvc.Html
@using n.Helpers
@inherits n.Models.BasePage
<nav class="menu main col100" role="navigation">
<div class="inner">
<ul class="greyDark">
@{
PageDataCollection allChildren = DataFactory.Instance.GetChildren(PageReference.StartPage);
PageDataCollection allGrandChildren = new PageDataCollection();
allChildren.Insert(0, PageReference.StartPage.GetPage()); //Add Startpage to collection
IEnumerable<PageData> filteredChilds = FilterForVisitor.Filter(allChildren).Where(p => p.IsVisibleOnSite() && p.VisibleInMenu);
//First level
foreach (PageData item in filteredChilds)
{
if (item.HasChildren() && item.GetPageReference() != PageReference.StartPage)
{
allGrandChildren.Add(DataFactory.Instance.GetChildren(item.GetPageReference())); //add this childs children for second level
}
var act = string.Empty;
<li>
@if (CurrentPage.LinkURL == item.LinkURL || item.GetPageReference() == CurrentPage.ParentLink && CurrentPage.ParentLink != PageReference.StartPage)
{
act = "active";
}
<a class="@act" href="/@item.URLSegment.ToString()">
@item.Name
</a>
</li>
}
}
</ul>
</div>
</nav>
<nav class="menu section col100" role="navigation">
<div class="inner">
<ul class="greyDark">
@{
IEnumerable<PageData> filteredGrandChildren = FilterForVisitor.Filter(allGrandChildren).Where(p => p.IsVisibleOnSite() && p.VisibleInMenu);
//Second level
foreach (PageData item in filteredGrandChildren.Where(p => p.ParentLink == CurrentPage.GetPageReference() || p.ParentLink == CurrentPage.ParentLink))
{
var act = string.Empty;
<li>
@if (CurrentPage.LinkURL == item.LinkURL)
{
act = "active";
}
<a class="@act" href="@Url.PageUrl(item.StaticLinkURL)">
@item.Name
</a>
</li>
}
}
</ul>
</div>
</nav>
Published by danbad
.net developer working with web
View all posts by danbad
Take a look ar AlloyTech MVC samples. There are some “improvements” over your approach 🙂
I have refactored my code and it now looks much like the Alloy one.
Great! If we go even further – much of the code could be removed and extracted to useful extension method 🙂
Of course that has allready been done =)
@Helper.RenderMenu(allGrandChildren.Where(p => p.ParentLink == CurrentPage.GetPageReference() || p.ParentLink == CurrentPage.ParentLink),CurrentPage)
The code does not work well in admin mode. The menu does respect permissions when admin uses the “view as” settings.
Ok, well if you find the problem please share, havent worked with personalization so it have never been tested.
That menu is not the best code I have written, was my first epi7 code. Have a better top menu nowdays.