Extending the Episerver global menu

Mari Jørgensen 07.12.2016 07:00:00

My mission

So, lets say I have an awsome plugin that does some magic stuff. I want to add a new global menu item called "Custom tools" with a sub menu item called "Overview". I want to keep the menu context with "Overview" as active menu item,  even If I navigate between several actions inside my controller. Clicking "Overview" should always take me back to Index view.

The screenshots below illustrates what I'm trying to achieve. Notice how the menu is kept active, even if the url changes (loading antother view/action).

 

Got it? Ok, let's look at some code!

First step is to create the controller for the plugin, a simple controller with two action methods:

public class CustomToolsController : Controller
{
   public ActionResult Index()
  {
     return View();
  }
  public ActionResult Other()
 {
     return View();
 }
}

RouteMenuItem to the rescue

Next step is to create a new class that implement the IMenuProvider interface, decorate it with the [MenuProvider] attribute and create your menu items in the GetMenuItems() method. And, as you may have guessed from the heading above, this is where RouteMenuItem comes to the rescue. 

 [MenuProvider]
public class MyMenuProvider : IMenuProvider
{
private string _url;
public MyMenuProvider(RequestContext requestContext)
{
url = (new UrlHelper(requestContext)).Action("Index", "CustomTools");
}
public IEnumerable<MenuItem> GetMenuItems()
{
var sectionMenuItem = new SectionMenuItem("Custom tools", "/global/mycustomtool");
sectionMenuItem.IsAvailable = (request) => PrincipalInfo.HasEditAccess;
var subMenuItem = new RouteMenuItem("Overview", "/global/mycustomtool/index",
new RouteValueDictionary(new {controller="CustomTools"})); // need to match controller name
subMenuItem.Url = _url;

return new MenuItem[]
{
sectionMenuItem,
subMenuItem
};
}
}

If you are new to MenuProvider I recommend reading through the documentation: http://world.episerver.com/documentation/developer-guides/CMS/user-interface/Extending-the-navigation/