Layout Sample in MVC

Layout Sample in MVC

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

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

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

image.png

  • Step 7

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

image.png

  • Step 8

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

image.png

  • Step 9

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

image.png

  • 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()".

image.png

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

image.png

  • Step 12

Run the project and you can see that the Index view has been rendered with the layout.

image.png

<< Day 5

>> Day 7