ASP.NET Core 2.0 MVC Areas

Problem

How to structure a large ASP.NET Core MVC application into logical groupings.

Solution

In an empty project, update Startup class to add services and middleware for MVC.

Create a folder structure like the following.


Add files to Controllers and Views folders (Area1 shown below).


Add [Area] attribute to Controllers in Area1 and Area2 folder.

Discussion

MVC separates the application concerns using Models, Views, and Controllers. For larger applications, Areas provide a way to group these three concerns into another high-level grouping. For instance, you may want to split your application into modules, each one containing its own MVC structure.

For routing purposes, there is another route parameter area available (in addition to the controller and action). You could think of areas as namespaces, under which Controllers live. The arearoute parameter is also available as ambient value if it’s in context of the current request, see Routing. Below, you can see how area parameter for Area1 links is left out since this page is in Area1 (see also Link Generation section below).

In order to use Areas in your project, you first set up a folder structure with Areas root folder and sub-folders for each area (along with its Controller, Models, and Views). Note that the folder structure is important for Views because MVC will search for the Views in the following sequence:

Once the folder structure is in place, you can decorate controllers with [Area] attribute

Link Generation

Below is a table of route parameters required when generating a link from one location to a different location, location being {area}/{controller}/{action},

Missing route parameters mean that MVC will pick those values up from the request context. I personally find it easier to specify all the route parameters to make maintenance easier. The sample for this post has links to various pages to show how ambient values work:

Layout Pages

Razor pages inside Areas folder can use the Layout page located outside it (e.g. in /Views/Shared folder). You can define a separate Layout page for each Area too. Yet another approach is to define a common Layout page outside Areas folder and Layout pages inside Areas folder use them as their layout, creating a nested Layout page structure. Below is a Layout page for Area2 that uses shared layout page (note you need an absolute path to shared layout).

Source Code

GitHub