瀏覽網站的時候會發現,好多網站中,每個網頁的基本框架都是一樣的,比如,最上面都是網站的標題,中間是內容,最下面是網站的版權、開發提供商等信息:
在這些網頁中,表頭、底部的樣式和內容都是一樣的,不同的只是中間的內容。
因此在制作網站時,可以將這些共同的東西分離出來,放到“窗體母版頁”中,在需要的時候嵌套就可以。
下面就開始行動(本文是以VisualStudio2013作為編程環境,可能在某些步驟與其他版本有所出入,請自行注意):
1、在項目中添加一Web窗體母版頁test.Master:右鍵項目—添加—新建項—Web窗體母版頁;
?12345678910111213141516171819 | <%@ Master Language= "C#" AutoEventWireup= "true" CodeBehind= "test.master.cs" Inherits= "Web.test1" %> <meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" >
<title></title>
<asp:ContentPlaceHolder ID= "head" runat= "server" >
<form id= "form1" runat= "server" >
<div>
</asp:contentplaceholder>
</div>
</form> <!--html> |
2、在窗體母版頁test.Master的標記之間添加CSS、JS等引用(這里先只添加CSS文件為例):
?12345 | <link href= "css/common.css" rel= "stylesheet" > <%--添加引用CSS文件--%> <meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" > <title></title> </asp:contentplaceholder> |
3、編輯窗體母版頁test.Master,添加每個網頁的公共內容(此處以網頁布局為上圖的布局為例,三個div的css樣式就暫不說明):
?123456789101112131415 | <form id= "form1" runat= "server" >
<div id= "top" > <%--每個網頁的公共樣式:網頁頭部--%>
<h1>某某某網站</h1>
</div>
<div id= "main" > <%--每個網頁的不同樣式:網頁主體內容--%>
<%--此處為每個嵌套此母版的各個網頁的不同內容--%>
</asp:contentplaceholder>
</div>
<div id= "footer" > <%--每個網頁的公共樣式:網頁版權信息區--%>
<p>版權所有:******</p>
</div> </form> |
4、在每個網頁中嵌套窗體母版頁test.Master:右鍵項目—添加—新建項—包含母版頁的Web窗體test.aspx,在選擇母版頁對話框中選擇test.Master,確定,生成的網頁為:
?12345 | <%@ Page Title= "/" Language=" C# " MasterPageFile=" ~/common.Master " AutoEventWireup=" true " CodeBehind=" test2.aspx.cs " Inherits=" Web.test2" %> </asp:content> </asp:content> |
此時這個窗體test.aspx和母版頁test.Master的運行效果是一樣的,接下來就是加上每個網頁中的不同的內容。
5、此時,網頁test.aspx中ContentPlaceHolderID=“head”和ContentPlaceHolderID=“contentPlaceHolder”的就相當于母版頁test.Master中對應的。所以假如每個網頁都會有相同部分,就可以把相同部分寫在母版頁的相應位置,而將每個網頁的不同內容寫在ContentPlaceHolderID=“contentPlaceHolder”的中。
比如,第4步中,這個test.aspx已經嵌套了這個樣式,它的主題內容為 “ 網站內容 網站內容 網站內容 網站內容…… ”,則test.aspx中的代碼為:
?123456 | <%@ Page Title= "/" Language=" C# " MasterPageFile=" ~/common.Master " AutoEventWireup=" true " CodeBehind=" test2.aspx.cs " Inherits=" Web.test2" %> </asp:content>
<p>網站內容 網站內容 網站內容 網站內容…… </p> </asp:content> |
假如我又建了一個名為test1.aspx的網頁,除了與test1.aspx中的主體內容不一樣之外,其他都一樣,那么就可以讓test1.aspx嵌套母版頁test.Master,代碼為:
?