Layout For All Views Sample in MVC

Layout For All Views Sample in MVC

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...".

image.png

Step 2

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

Click on the "Add" button.

image.png

Step 3

Name the controller as in the following:

image.png

Step 4

Now we need to create a view.

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

image.png

Step 5

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

image.png

Step 6

Add content to the body part.

image.png

Step 7

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

image.png

Step 8

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

image.png

Step 9

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

image.png

Step 10

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

image.png

Step 11

Design your desired layout in _Layout.cshtml.

image.png

Step 12

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

image.png

Step 13

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

image.png

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.

image.png

Step 15

Run the project and you can see the Index view is rendered with layout.

image.png

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