A fast-paced cookbook with recipes covering all that you wanted to know about developing with ASP.NET MVC
In this recipe, we will take a look at how to create a master page and associate it with our view. Part of creating a master page is defining placeholders for use in the view. We will then see how to utilize the content placeholders that we defined in the master page.
<table>
<tr>
<td>
</td>
<td>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1"
runat="server"></asp:ContentPlaceHolder>
</td>
<td>
</td>
</tr>
</table>
<table>
<tr>
<td>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1"
runat="server"></asp:ContentPlaceHolder>
</td>
<td>
<asp:ContentPlaceHolder ID="MainContent"
runat="server"></asp:ContentPlaceHolder>
</td>
<td>
<asp:ContentPlaceHolder ID="ContentPlaceHolder2"
runat="server"></asp:ContentPlaceHolder>
</td>
</tr>
</table>
public ActionResult CustomMasterDemo()
{
return View();
}
Views/Home/CustomMasterDemo.aspx:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent"
runat="server">
<h2>Custom Master Demo</h2>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head"
runat="server">
<meta name="description" content="Here are some keywords for our
page description.">
</asp:Content>
<asp:Content ID="Content3"
ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div style="width:200px;height:200px;border:1px solid #ff0000;">
<ul>
<li>Home</li>
<li>Contact Us</li>
<li>About Us</li>
</ul>
</div>
</asp:Content>
<asp:Content ID="Content"
ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
<div style="width:200px;height:200px;border:1px solid #000000;">
<b>News</b><br/>
Here is a blurb of text on the right!
</div>
</asp:Content>
This particular feature is a server-side carry over from web forms. It works just as it always has. Before being sent down to the client, the view is merged into the master file and processed according to the matching placeholder IDs.
In the previous recipe, we took a look at how to build a master page. In this recipe, we are going to take a look at how to control what master page to use programmatically. There are all sorts of reasons for using different master pages. For example, you might want to use different master pages based on the time of day, if a user is logged in or not, for different areas of your site (blog, shopping, forum, and so on).
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
string masterName = "";
if (DateTime.Now.Second % 2 == 0)
masterName = "Site2";
else
masterName = "Site";
return View("Index", masterName);
}
This method of controlling which master page is used by the view is built into the MVC framework and is the easiest way of performing this type of control. However, having to dictate this type of logic in every single action would create quite a bit of fluff code in our controller. This option might be appropriate for certain needs though!