Skip to main content

Layout in ASP.NET MVC

Layout is a View which contain all the common html markup of the site template and by inheriting it we can create other views, which help to not rewrite the same markup of each html or view file and also help for consistent look and feel throughout the site.



To explain the common html code, in above image you can see the page layout on which you reading this article, if you notice the common sections on the all page are Header, Main Content, Footer and Right Section. Except Main Body all are same throughout this website, the Main body contain the articles.

To understand as example here we  are creating a View under folder Views/Shared and called it as _Layout.cshtml.
<html>
<body>
<div id="header"> Header Panel</div>
<div id="body"> Main Body </div>
<div id="right"> Right Panel</div>
<div id="footer"> Footer Panel </div>
</html>

now in the above html always per page div content will change is div 'body'. Now question is how to make body div which will change for every View/Page in site, to achieve this razor have @RenderBody directive.
e.g:
<html>
<body>
<div id="header"> Header Panel </div>
<div id="body"> @RenderBody </div>
<div id="right"> Right  Panel </div>
<div id="footer"> Footer  Panel </div>
</html>

Now every view which you creating and adding layout as _Layout.cshtml then child view content showing in between only div body
e.g:
ChildPage.cshtml
@{
Layout = ~/Views/Shared/_Layout.cshtml
}
Hello world from render body

then as complete it render as
<html>
<body>
<div id="header"> Header Panel  </div>
<div id="body"> Hello world from render body </div>
<div id="right"> Right Panel  </div>
<div id="footer"> Footer Panel  </div>
</html>
The above example help you to understand how you can make view section which is not common for all Views in website.