Friday 4 August 2017

Create Layout View



To create a new layout view in Visual Studio, right click on shared folder -> select Add -> click on New Item..
In the Add New Item dialogue box, select MVC 5 Layout Page (Razor) and give the layout page name as "_myLayoutPage.cshtml" and click Add.
Rendering Methods
You will see _myLayoutPage.cshtml as shown below.
_myLayoutPage.cshtml:
            
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Now, add the <footer> tag with the RenderSection("footer",true) method alongwith some styling as shown below. Please notice that we made this section as required. This means any view that uses _myLayoutPage as its layout view must include a footer section.
_myLayoutPage.cshtml :
            
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div>
        @RenderBody()
    </div>
    <footer class="panel-footer">
        @RenderSection("footer", true)
    </footer>
</body>
</html>

Now, let's use this _myLayoutPage.cshtml with the Index view of HomeController.
You can add an empty Index view by right clicking on Index action method of HomeController and select Add View. Select Empty as a scaffolding template and _myLayoutPage.cshtml as layout view and click Add.
Add Index View
This will create Index.cshtml as shown below.
Index view:

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

    <h2>Index</h2>

So now, we have created Index view that uses our _myLayoutPage.cshtml as a layout view. We will now add footer section along with some styling because _myLayoutPage requires footer section.
Index view:

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

<div class="jumbotron">
    <h2>Index</h2>
</div>
<div class="row">
    <div class="col-md-4">
        <p>This is body.</p>
    </div>
    @section footer{
        <p class="lead">
            This is footer section.
        </p>
    }
</div>


Now, run the application and you will see Index view will contain body and footer part as shown below.
Index View
Thus, you can create new layout view with different rendering methods.

No comments:

Post a Comment