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...".
Step 2
Select "MVC 5 Controller - Empty" to add an empty controller.
Click on the "Add" button.
Step 3
Name the controller as in the following:
Step 4
Now we need to create a view.
Right-click on "Index" and select "Add View...".
Step 5
Name the view and select "Empty (without model)" as the template. Click on the "Add" button.
Step 6
Add content to the body part.
Step 7
Right-click on "Views" and select "Add" >> "New Folder".
Step 8
Name the folder "Shared", this will create a "Shared" folder under the view.
Step 9
Right-click on the "Shared" folder and select "Add" >> "View…".
Step 10
Name the view as "_Layout" and select "Empty (without model)" as the template.
Step 11
Design your desired layout in _Layout.cshtml.
Step 12
Right-click on "Views" and select "Add" >> "View…".
Step 13
Name the view as "_ViewStart" and it will add _ViewStart.cshtml under Views.
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.
Step 15
Run the project and you can see the Index view is rendered with layout.
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