Layout For All Views Sample in MVC, Day 7

Introduction

This article shows how to set a layout link once for all views in MVC.

Step 1

Create a MVC project from the "Empty" template.

Right-click on "Controllers" and select "Add" >> "Controller...".

1 Create a MVC

Step 2

Select "MVC 5 Controller - Empty" to add an empty controller.

Click on the "Add" button.

2 mvc controller

Step 3

Name the controller as in the following:

3 home controller

Step 4

Now we need to create a view.

Right-click on "Index" and select "Add View...".

4 create a view

Step 5

Name the view and select "Empty (without model)" as the template. Click on the "Add" button.

5  view and select 

Step 6

Add content to the body part.

6 body part

Step 7

Right-click on "Views" and select "Add" >> "New Folder".

7 New Folder

Step 8

Name the folder "Shared", this will create a "Shared" folder under the view.

8 Shared 

Step 9

Right-click on the "Shared" folder and select "Add" >> "View…".

9 folder and select

Step 10

Name the view as "_Layout" and select "Empty (without model)" as the template.

10 Layout and select

Step 11

Design your desired layout in _Layout.cshtml.

11 Layout cshtml

 Step 12

Right-click on "Views" and select "Add" >> "View…".

12 Views and select

Step 13

Name the view as "_ViewStart" and it will add _ViewStart.cshtml under Views.

13 ViewStart

 Step 14

In a previous article we saw that _Layout.cshtml link is set in each view. But rather than setting in each view we set the _Layout.cshtml link in _ViewStart.cshtml under the views. And this layout will be implemented in all views. So we need not set a layout link in each view.

14 ViewStart cshtml 

 Step 15

Run the project and you can see the Index view is rendered with layout.
 
15 Index view 
To verify you can add one more view and render it in a browser, the same layout is rendered with the recently added view.

<< Day 6                                               >> Day 8

Up Next
    Ebook Download
    View all
    Learn
    View all