Get Current Area Name in View or Controller

C#asp.net MvcRazor

C# Problem Overview


How do you get the current area name in the view or controller?

Is there anything like ViewContext.RouteData.Values["controller"] for areas?

C# Solutions


Solution 1 - C#

From MVC2 onwards you can use ViewContext.RouteData.DataTokens["area"]

Solution 2 - C#

HttpContext.Current.Request.RequestContext.RouteData.DataTokens["area"]

Solution 3 - C#

You can get it from the controller using:

ControllerContext.RouteData.DataTokens["area"]

Solution 4 - C#

In ASP.NET Core 1.0 the value is found in

ViewContext.RouteData.Values["area"];

Solution 5 - C#

I just wrote a blog entry about this, you can visit that for more details, but my answer was to create an Extension Method, shown below.

The key kicker was that you pull the MVC Area from the .DataTokens and the controller/action from the .Values of the RouteData.

public static MvcHtmlString TopMenuLink(this HtmlHelper htmlHelper, string linkText, string controller, string action, string area, string anchorTitle)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        var url = urlHelper.Action(action, controller, new { @area = area });

        var anchor = new TagBuilder("a");
        anchor.InnerHtml = HttpUtility.HtmlEncode(linkText);
        anchor.MergeAttribute("href", url);
        anchor.Attributes.Add("title", anchorTitle);

        var listItem = new TagBuilder("li");
        listItem.InnerHtml = anchor.ToString(TagRenderMode.Normal);
        
        if (CheckForActiveItem(htmlHelper, controller, action, area))
            listItem.GenerateId("menu_active");

        return MvcHtmlString.Create(listItem.ToString(TagRenderMode.Normal));
    }

    private static bool CheckForActiveItem(HtmlHelper htmlHelper, string controller, string action, string area)
    {
        if (!CheckIfTokenMatches(htmlHelper, area, "area"))
            return false;

        if (!CheckIfValueMatches(htmlHelper, controller, "controller"))
            return false;

        return CheckIfValueMatches(htmlHelper, action, "action");
    }

    private static bool CheckIfValueMatches(HtmlHelper htmlHelper, string item, string dataToken)
    {
        var routeData = (string)htmlHelper.ViewContext.RouteData.Values[dataToken];

        if (routeData == null) return string.IsNullOrEmpty(item);

        return routeData == item;
    }

    private static bool CheckIfTokenMatches(HtmlHelper htmlHelper, string item, string dataToken)
    {
        var routeData = (string)htmlHelper.ViewContext.RouteData.DataTokens[dataToken];
        
        if (dataToken == "action" && item == "Index" && string.IsNullOrEmpty(routeData))
            return true;

        if (dataToken == "controller" && item == "Home" && string.IsNullOrEmpty(routeData))
            return true;

        if (routeData == null) return string.IsNullOrEmpty(item);

        return routeData == item;
    }

Then you can implement it as below :

<ul id="menu">
@Html.TopMenuLink("Dashboard", "Home", "Index", "", "Click here for the dashboard.")
@Html.TopMenuLink("Courses", "Home", "Index", "Courses", "List of our Courses.")
</ul>

Solution 6 - C#

I created an extension method for RouteData that returns the current area name.

public static string GetAreaName(this RouteData routeData)
{
    object area;
    if (routeData.DataTokens.TryGetValue("area", out area))
    {
        return area as string;
    }

    return null;
}

Since RouteData is available on both ControllerContext and ViewContext it can be accessed in your controller and views.

It is also very easy to test:

[TestFixture]
public class RouteDataExtensionsTests
{
    [Test]
    public void GetAreaName_should_return_area_name()
    {
        var routeData = new RouteData();
        routeData.DataTokens.Add("area", "Admin");
        routeData.GetAreaName().ShouldEqual("Admin");
    }

    [Test]
    public void GetAreaName_should_return_null_when_not_set()
    {
        var routeData = new RouteData();
        routeData.GetAreaName().ShouldBeNull();
    }
}

There is no need to check if RouteData.DataTokens is null since this always initialized internally.

Solution 7 - C#

Get area name in View (.NET Core 2.2):

ViewContext?.ActionDescriptor?.RouteValues["area"]

Solution 8 - C#

MVC Futures has an AreaHelpers.GetAreaName() method. However, use caution if you're using this method. Using the current area to make runtime decisions about your application could lead to difficult-to-debug or insecure code.

Solution 9 - C#

I know this is old, but also, when in a filter like ActionFilter, the context does not easily provide you with the area information.

It can be found in the following code:

var routeData = filterContext.RequestContext.RouteData;

if (routeData.DataTokens["area"] != null)
    area = routeData.DataTokens["area"].ToString();

So the filterContext is being passed in on the override and the correct RouteData is found under the RequestContext. There is a RoutData at the Base level, but the DataTokens DO NOT have the area in it's dictionary.

Solution 10 - C#

To get area name in the view, in ASP.NET Core MVC 2.1:

@Context.GetRouteData().Values["area"]

Solution 11 - C#

I dont know why but accepted answer is not working. It returns null with e.g ( maybe about mvc, i use .net core )

> http://localhost:5000/Admin/CustomerGroup

I always debug the variable and fetch data from in it.

Try this. It works for me

var area = ViewContext.RouteData.Values["area"]

Detailed logical example

Layout = ViewContext.RouteData.Values["area"] == null ? "_LayoutUser" : "_LayoutAdmin";

Solution 12 - C#

I know this is a very very old post but we can use the Values Property exactly the same way as the DataTokens

Url.RequestContext.RouteData.Values["action"] worked for me.

Solution 13 - C#

Asp .Net Core 3.1

Scenario: I wanted to retrieve the current area name in a ViewCompnent Invoke method.

  public IViewComponentResult Invoke()
  {
       string areaName = this.RouteData.Values["area"];

       //Your code here...

       return View(items);
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser202448View Question on Stackoverflow
Solution 1 - C#artvolkView Answer on Stackoverflow
Solution 2 - C#SlavaView Answer on Stackoverflow
Solution 3 - C#Matt PennerView Answer on Stackoverflow
Solution 4 - C#zerox981View Answer on Stackoverflow
Solution 5 - C#christeseneView Answer on Stackoverflow
Solution 6 - C#Ben FosterView Answer on Stackoverflow
Solution 7 - C#SZLView Answer on Stackoverflow
Solution 8 - C#LeviView Answer on Stackoverflow
Solution 9 - C#gcoleman0828View Answer on Stackoverflow
Solution 10 - C#NetstepView Answer on Stackoverflow
Solution 11 - C#FarukestView Answer on Stackoverflow
Solution 12 - C#Joao Nunes da SilvaView Answer on Stackoverflow
Solution 13 - C#JohnnyJaxsView Answer on Stackoverflow