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.
Open your MVC project in Visual Studio. Add a view model for products. Add a new controller with an action that handles displaying the product detail page.
ASP.NET Core MVC Area is a feature to divide your large application into a small logical group. Areas help to manage application in a better way to separate each functional aspect into different Areas. Each Area has its own MVC structure by having subfolders for Models, Views, and Controller.
In ASP.NET MVC, every controller class name must end with a word "Controller". For example, the home page controller name must be HomeController , and for the student page, it must be the StudentController . Also, every controller class must be located in the Controller folder of the MVC folder structure.
In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With