How do you get the current area name in the view or controller?
Is there anything like ViewContext.RouteData.Values["controller"]
for areas?
How do you get the current area name in the view or controller?
Is there anything like ViewContext.RouteData.Values["controller"]
for areas?
You can get it from the controller using:
I created an extension method for
RouteData
that returns the current area name.Since
RouteData
is available on bothControllerContext
andViewContext
it can be accessed in your controller and views.It is also very easy to test:
There is no need to check if
RouteData.DataTokens
is null since this always initialized internally.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.
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.
Then you can implement it as below :
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:
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.