Creating Layout (Master) Pages In MVC

Introduction

This article explains how we can create the Layout (Master) page in MVC 5. Also, it explains the components of Master Page.

Creating Layout Pages
  1. Create a new MVC Project.

    MVC Project

    MVC Project

  2. Add MVC Layout page in Share folder.
    Note: Share folder pages can be used across the project.

    Folder

    Folder

  3. Add the below content to the Layout page.

    code

    Nav- Nav tags are generally used for navigation bar. We can add links to navigate between the pages.

    @RenderSection- Render section is just like a place holder where we can place our code that we can inject from the content page. If we make render section property true, we must need to add this section in all the pages which are used in this layout page, otherwise it will go through as a not implemented error. If we want to make this an option, we need to set it to false.

    @RenderBody- RenderBody is a place holder to display the content of the View.

    Header & Footer- These are useful to display the header and footer information.

  4. Add Controller and its View to create your page.

    Controller

    Controller

    Controller

  5. Select a new layout page while creating the View.

     new layout page

     new layout page

  6. The below Index View is created by using _RKMaster.cshtml page. In general, if you use _Layout.cshtml, it doesn't display here because it is set in the global default Master page. If we want to set our Layout page as default layout page, we need to set it in _ViewStart.html page, as shown below.

    code

    code

  7. Add the Render section and page content in the View.

    code

  8. Configure your Controller in Route Config to take it as default, and execute the project.

    code

  9. Final View- The header, nav, and footer are coming from the Master Layout page, while the section and page body are rendering from the View page.

    output

Hope this article helps you in understanding the Layout pages and its content.

Ebook Download
View all
Learn
View all