Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the current MVC Area name in a .cshtml file in ASP.NET Core

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.

like image 387
devfric Avatar asked Feb 24 '16 12:02

devfric


People also ask

How can I see details in MVC?

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.

What is area in ASP.NET MVC core?

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.

What must the controller be named in ASP.NET MVC and what folder does it have to be specifically saved under?

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.

How do you reference a controller model?

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.


1 Answers

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>
like image 191
Shyju Avatar answered Oct 03 '22 23:10

Shyju