Layout Sample in MVC, Day 6

Introduction

In this article we will see how to create a layout for a view in MVC.

  • Step 1

Create a MVC project from the "Empty" template.

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

Empty template

  • Step 2

Select "MVC 5 Controller - Empty" to add an empty controller. Click on the "Add" button.

MVC 5 Controller
  • Step 3

Name the controller as in the following:

home controller
  • Step 4
Now we need to create a view.
Right-click on "Index" and select "Add View...".
 
Index select
  • Step 5

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

Add button
  • Step 6

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

Views and select
  • Step 7

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

Shared
  • Step 8

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

Shared 1 
  • Step 9
Name the view as "_Layout" and select "Empty (without model)" as the template.

Layout and select
  • Step 10

Design your desired layout in _Layout.cshtml.

Here we create a header, footer, side bar and content area. The header, footer and side bar should be shown in all pages, so we create them in _Layout.cshtml. The variable portion of the site is the content area, where content is changed dynamically. In ASP.NET we use a "ContentPlaceHolder", in the same way in MVC we use "RenderBody()".

Layout cshtml
  • Step 11

Attach a layout page to Index.cshtml. Set the link of _Layout.cshtml in Index.cshtml.

Add the content in the body part of Index.cshtml.

Layout cshtml 11
  • Step 12
Run the project and you can see that the Index view has been rendered with the layout.
 
header 
<< Day 5                                                     >> Day 7


Similar Articles