EPiServer 7 MVC Top menu

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>

6 thoughts on “EPiServer 7 MVC Top menu

  1. Of course that has allready been done =)

      @Helper.RenderMenu(allGrandChildren.Where(p => p.ParentLink == CurrentPage.GetPageReference() || p.ParentLink == CurrentPage.ParentLink),CurrentPage)

  2. The code does not work well in admin mode. The menu does respect permissions when admin uses the “view as” settings.

    1. 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.

Leave a comment