Subscribe to my feed here: http://feeds.jeffreypalermo.com/jeffreypalermo
We are used to master pages and applying them to ASPX pages. Then we pull small parts of the view into user controls or ASCX. In ASP.NET MVC, we use ASCX files as partial views because the user control model is so baked into our thinking.
I propose that ASCX does not provide much benefit in ASP.NET MVC. It’s usefulness may end with using the extension as a naming convention for the easy identification of partial views. Beyond that, it’s pretty thin.
Consider the following scenario where only the ASPX extension is used for views and partial views. The partial views, because they are ASPX files, are able to leverage master pages for small-scale templating. Using master pages for nested templates around partials gives us a whole new dynamic with which to break down web pages in ASP.NET MVC.
The above screen shot is the screen we are going for. We want consistent formatting for two partials that would hold charts. Here is a code sample based on the basic project template. I have enhanced the Home Index.aspx view as follows:
/Views/Home/Index.aspx
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
"float:left">"chart1"); %>
"float:left">"chart2"); %>
"clear:both">
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc"
title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
</asp:Content>
You see we are rendering two partials, chart1 and chart2. Here is the code for the partials:
/Views/Shared/Chart1.aspx
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/ChartLayout.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ContentPlaceHolderID="Main" runat="server">
Chart 1 goes here
</asp:Content>
/Views/Shared/Chart2.aspx
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/ChartLayout.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ContentPlaceHolderID="Main" runat="server">
Chart 2 goes here
</asp:Content>
Notice that each of these partials declare a master page. Let’s see what templating the master page gives us:
/Views/Shared/ChartLayout.master
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>"border:solid 4px green;padding:100px;margin:20px">
"Main" runat="server">
The css styling is what to look for. Each partial is surrounded by a green border with padding and margin. This formatting is consistently applied by the master page declared in both the partials. The main view doesn’t care about this partial formatting because it belongs to the partial. Look again to the screenshot above. Because we used ASPX partial views, we gained the formatting capability of master pages.