Reputation: 7532
I can get the current controller name and action name in a _Layout.cshtml
by doing the following
var controller = ViewContext.RouteData.Values["controller"].ToString();
var action = ViewContext.RouteData.Values["action"].ToString();
However when I try get the area
var area = ViewContext.RouteData.Values["area"].ToString();
it doesn't work as only 2 keys exist in that object("controller" and "action")
I examined the ViewContext.RouteData
object and cannot get a value for the current Area name.
The previous answers for the previous version of ASP.net
don't work for me.
Upvotes: 5
Views: 4596
Reputation: 218842
Thanks to Pranav's comment! GetNormalizedRouteValue
method is now public. So you can call RazorViewEngine.GetNormalizedRouteValue
method in your view to the the area name when you pass the key as "area".
<h2> @RazorViewEngine.GetNormalizedRouteValue(ViewContext, "area") </h2>
RazorViewEngine
class belongs to Microsoft.AspNetCore.Mvc.Razor
namespace. So make sure you have a using statement to import that in your view.
@using Microsoft.AspNetCore.Mvc.Razor
GetNormalizedRouteValue
method is doing the same as explained in the previous version of answer. You can see the source code here
This totally worked for me in a razor view (MVC6).
@using Microsoft.AspNet.Routing
@{
var myAreaName = string.Empty;
object areaObj;
if (ViewContext.RouteData.Values.TryGetValue("area", out areaObj))
{
myAreaName = areaObj.ToString();
}
}
<h1>@myAreaName</h1>
Upvotes: 14