Exposing Route Data for Dynamic Navigation in .NET MVC

Sometimes, for example dynamic navigation, we may need to expose data about the current URL, this post looks at using ViewContext to expose this data.

The scenario is as follows, you know a user is part of a policy that allows administration access, but your layout caters for both regular users and an administration dashboard. We use a partial to load the navigation, but we only want to show this when the route is for a specific area.

ViewContext.RouteData.Values["Area"]?.ToString()

Let’s take a look at the above code. We are using ViewContext to access the route data and looking for a specific area, you can also look for a controller and action as well if you want. We then simply put this into an if statement and load the partial as required. You can see an example below:

@if (ViewContext.RouteData.Values["Area"]?.ToString() == "Admin")
{
    <partial name="Navigation/_Admin"/>
}

There you have it!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.