ASP.NET Core 2.0 MVC Layout Pages

Problem

How to share common visual elements, code blocks and directives in ASP.NET Core MVC.

Solution

In an empty project amend Startup class to add services and middleware for MVC:

Add a service and model:

Add a controller with action method returning ViewResult:

Add _Layout.cshtml:

Add Index.cshtml:

Add _ViewImports.cshtml:

Add _ViewStart.cshtml:

Discussion

ASP.NET Core MVC provide ways to reuse and share visual elements and common code between different views. These are 1) Layout Page 2) Start Page 3) Imports Page.

Layout Page

These are used to share common visual elements in your pages and provide a consistence look and feel throughout your application.

Layout page is added to the Views/Shared folder and is named (as a convention) _Layout.cshtml. There can be more than one layout pages in your application too.

Views have a Layout property through which they set the layout to use. The layout page is searched in controller specific folder and then in shared folder. Layout page calls @RenderBody method to render the contents of a view.

Layout page can also use @RenderSection to decide where sections defined in views will be placed. These sections can be required or optional. Views define the contents of a section using @section syntax. Layout page can check if a section is defined in the view and act accordingly using IsSectionDefined method on the view:

Import Page

As we discussed in Razor post, views canĀ  use directives for a number of things, e.g. importing namespaces (@using), injecting dependencies (@inject) and declaring model type (@model). MVC provides an import page to declare directives common to one or more views.

Import page is added usually in Views folder and is named _ViewImports.cshtml. It can also be added to other folders (e.g. controller specific views folder) however, in this case it will apply to views inside this folder (and its subfolders).

In case of multiple import pages, either the directives close to the views are used (e.g. @model, @inject) or all are combined (@using, @addTagHelper).

Start Page

MVC provides a mechanism to run code common to all views using a start page. Start page run before every view, except for layout page and partial views.

Start page is added usually in Views folder and is named _ViewStart.cshtml. There can be multiple start pages, in which case they will run in hierarchical order, from root to subfolders.

Start page is often used to set the Layout page for all the views in a folder.

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Mvc.Layout

Leave a Reply