In previous post MVC4 Web Application
projects in VS11 I touched upon how you can use VS11 to create MVC4 web applications. In this project I will discuss
little about setting up view and mainly a very nice concept introduced with ASP.Net, Master Pages.
We have all used Master Pages in ASP.Net to put together common rendering tasks across all pages into one
common page. In MVC4 this concept is carried on. There is only one change in MVC4. There is no term as
Master Page. MVC4 refer to master page as Layout. If you look at the structure of the project
files created by VS11, you will notice file named _Layout.cshtml. This is master page or
layout for your MVC4 web application. Following snippet shows how it looks in my sample project.
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
("~/Content/css")" rel="stylesheet" type="text/css" />
("~/Content/themes/base/css")" rel="stylesheet" type="text/css" />
<div style="background-color: #f77b34;color: #ffffff;">
Copyright © ByteBlocks.com
Looks very familiar to what you are used to seeing in master page of ASP.Net applications. I will explain
more about Layout in MVC4.
_ViewStart.cshtml and _Layout.cshtml
You must be asking how does MVC framework know what layout file to use and what other files are there
in Views folder in your project. MVC framework look for _Viewstart.cshtml file in
Shared folder in your installation. This is the file that contains directives for which layout file to
use. Following snippet shows how it looks in sample application.
Layout = "~/Views/Shared/_Layout.cshtml";
As you can see that _Viewstart.cshtml has one line that sets Layout property to location of
file that is to be used for master layout of the pages. This is how MVC framework knows about
master page of your mvc application. If you set this property to null, this means
that you do not want to use any master page or layout for your view. If you look inside
Error.cshtml file in your project, you will notice following lines at the top of the
file directing the framework that it does not want to use any layout for the page.
Layout = null;
Now you are asking how does MVC framework know where to include content of individual views inside
layout. If you look at code snippet at top of this post, you will notice that we are calling
RenderBody method. This is the method that is responsible for rendering
individual views and including their content in layout.
Above image shows how i used layout to display common content and individual view content on the page.
The top menu and footer was put in Layout file. The welcome message was put in Home > Index
This is simple explanation of how concept of master pages in MVC is implemented. In subsequent posts
i will use MVC term for master page and that is Layout.