Implementation of Master Page in MVC
using Razor
In asp.net
we all are familiar with Master page. Master page is used to create a common
layout for the web based application.
In Master
page we use Content Place Holder where we want to place other pages content.
Similarly we
use the concept of Master page in MVC. We create a View which will be common to
every page. Here we use @RenderBody() method instead of Content Place Holder.
For example:-
First of all
add MVC application using Visual Studio->File->Project->MVC 4
Now go to
view folder and add folder in which you can add your view which will work like
master page.
Figure 1
Now right
click to this folder and add view and give it a proper name. Now create your
complete Master page. And the place which you want to leave for other pages
content, add method @RenderBody().
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>main_layout</title>
</head>
<body>
<table>
<tr>
<td>
<table>
<tr style="height:50px">
<td style="width:100px">@Html.ActionLink("Home","Index","Home")</td>
<td style="width:100px">@Html.ActionLink("Training","Training","Home")</td>
<td style="width:100px">@Html.ActionLink("Services","Services","Home")</td>
<td style="width:100px">@Html.ActionLink("Placement","Placement","Home")</td>
<td style="width:100px">@Html.ActionLink("Contact Us","Contact","Home")</td>
<td style="width:100px">@Html.ActionLink("Career","Career","Home")</td>
</tr>
</table>
</td>
</tr>
<tr style="height:200px">
<td>@RenderBody()</td>
</tr>
<tr style="height:200px">
<td>Add Your Footer Content Here</td>
</tr>
</table>
</body>
</html>
In this
master page I have simply showing the Menu and Footer part. In second row I have
simply added @RenderBody().
Now create a
Home controller and add action for index, training, services, placement,
contact and career.
Now create
view for each action and at the time of view creation select layout for master
page
Figure 2
Figure 3
Now go to
your other view and add your content. I am simply putting page name in this
content
Code of Index View
@{
ViewBag.Title = "Index";
Layout = "~/Views/Master/main_layout.cshtml";
}
<h2>Index</h2>
<table>
<tr>
<td>This is your home page.........</td>
</tr>
</table>
Similarly I added
other views and added the same content. Now execute the code and you will get
following output
Figure 4
Hope you
enjoyed the article. In my next article series I will discuss more about master
pages in MVC.
For any
query send mail at Malhotra.isha3388@gmail.com
No comments:
Post a Comment