Home / ASP.NET - MVC / How to create Layout View

How to create a Layout View in MVC

To create a new layout in Visual Studio, right-click on the folder shared --> Add --> New Item..

In the Add New dialog box, select MVC 5 Layout Page (Razor) and name the layout as "_myLayoutPage.cshtml", click Add.

You will see _myLayoutPage.cshtml as shown below.


<html>
<head>
    
    @ViewBag.Title
</head>
<body>
    
@RenderBody()
</body> </html>

Now add

tag with RenderSection("footer", true) method along with css as below. Please note that we have made this section mandatory. This means that any view that uses _myLayoutPage as its layout must have this footer section.

Example added RenderSection


<html>
<head>
    
    @ViewBag.Title
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    
@RenderBody()
@RenderSection("footer", true)
</body> </html>

Now, let's use this _myLayoutPage.cshtml with the HomeController's View Index.

You can add an empty Index view by right-clicking on the HomeController's Index and selecting Add View. Select Empty in scaffolding template and _myLayoutPage.cshtml. click Add

File Index.cshtml as shown below.

@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_myLayoutPage.cshtml";
}

Index

We have created an Index view using _myLayoutPage.cshtml as the view layout. Now we will add a footer with css because _myLayoutPage requires a footer.

@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_myLayoutPage.cshtml";
}

Index

This is body.

@section footer{

This is the footer section.

}

Now, run the application and you will see the view Index will contain body and footer as shown below.


Did you find this article helpful?

Support the author so they can write more quality articles!

Tư vấn lộ trình CNTT 🤖