ASP.NET 1.x中最突出的缺點之一是它缺少對頁面模板的支持。欠缺的是定義其他頁面可以繼承的“母版頁”能力。開發人員通過使用用戶控件(它們可以容易地在頁面之間複製)創建頁面來彌補這一缺陷。在ASP.NET 2.0中,由於加入了一個稱作“母版頁”的新增功能,所以不再需要這種技巧。想一想“可視化繼承”,您就會理解母版頁是幹什麼用的了。首先,您需要定義一個母版頁(其中包含您希望在其他頁面上顯示的內容),並且使用ContentPlaceHolder控件來定義子頁面可以將其內容插入的位置。然後,您需要生成子頁面—SPX文件,它使用(類似於)如下所示的指令來引用母版頁:
<%@ Page MasterPageFile="~/Foo.master" %>
在子頁面中,您使用Content控件來填寫母版頁中的佔位符。在瀏覽器中呈現子頁面,出現的內容將是在母版頁和子頁面中所定義內容的完美組合。
<%@ Master %>
<html>
<body leftmargin="0" topmargin="0" rightmargin="0"
bottommargin="0" marginheight="0" marginwidth="0"
>
<!-- Banner -->
<table cellspacing="0" cellpadding="0"
style="background-image: url('images/stripes.gif');
background-repeat: repeat-x, repeat-y" width="100%"
>
<tr><td align="center">
<span style="font-family: verdana; font-size: 36pt;
font-weight: bold; color: white"
>
Master Pages
</span><br>
<span style="font-family: verdana; font-size: 10pt;
font-weight: normal; color: white"
>
This banner provided by Master.master
</span>
</td></tr>
</table>
<!-- Placeholder for content between banner and footer -->
<form id="Content">
<asp:ContentPlaceHolder ID="Main" RunAt="server" />
</form>
<!-- Footer -->
<table width="100%"><tr><td align="center">
<span style="font-family: verdana; font-size: 8pt; color: red">
Copyright (c) 2004 by Me Inc. All rights reserved<br>
This footer provided by Master.master
</span>
</td></tr></table>
</body>
</html>
Master.master
<%@ Page MasterPageFile="~/Master.master" %>
<asp:Content ContentPlaceHolderID="Main" RunAt="server">
<table width="100%" height="256px"><tr><td align="center">
<h2>This content provided by Subpage.aspx</h2>
</td></tr></table>
</asp:Content>
圖1 Subpage.aspx
圖1中所示的應用程序使用母版頁來定義出現在每個頁面上的頁眉和頁腳。子頁面通過將Content控件插入母版頁的ContentPlaceHolder中,從而在頁眉和頁腳之間插入內容。您應該注意匹配的ID和ContentPlaceHolderID,以及母版頁中的@ Master指令。
母版頁在ASP.NET對象模型中得到了充分支持。System.Web.UI.Page類的特點是具有一個名爲Master的新屬性,該屬性使子頁面可以用編程方式來引用它的母版頁以及在其中定義的控件。母版頁可以嵌套,並且可以包含能夠在子頁面中重寫的默認內容。
<asp:ContentPlaceHolder ID="Main" RunAt="server">
This is default content that will appear in subpages unless
explicitly overridden
</asp:ContentPlaceHolder>
此外,應用程序可以在Web.config中指定默認的母版頁,如下所示:
<configuration>
<system.web>
<pages masterPageFile="~/Foo.master" />
</system.web>
</configuration>
單個子頁面享有重寫默認母版頁和指定它們自己的母版頁的自由。
最精彩的部分是Visual Studio® 2005中對母版頁的支持。當加載子頁面時,IDE將顯示母版頁中定義的內容的灰色、只讀版本,以及子頁面中定義的內容的全色、完全可編輯版本。區分這兩者很容易,並且如果要編輯屬於母版頁的內容,那麼您需要做的全部事情只是在IDE中打開母版頁。
有關母版頁的更多深入內容,請參閱本期雜誌相關的母版面的文章。