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