【Asp.net從零開始】:使用母版頁(Master Pages) (一):http://www.cnblogs.com/VortexPiggy/archive/2012/08/09/2629623.html
文章多參考MSDN,以及Web Applications Development with Microsoft .NET Framework 4 (MCTS的英文教材,所以有些許翻譯可能不是特別准確)
一.在內容頁中引用母版頁中的屬性,方法以及控件
內容頁中的代碼可以引用母版頁上的成員,包括母版頁上的任何公共屬性或方法以及任何控件。
1.在母版頁的.aspx文件中創建公共屬性
2.在內容頁的@Page指令下方,添加@MasterType屬性,將內容頁中的Master屬性綁定至需要引用的母版頁
<%@ MasterType virtualpath="~/Master1.master" %>
3.在內容頁中通過Mster.<屬性名>來引用母版頁成員。
代碼示例:
//在MasterPage中添加屬性
public String SharedInfo
{
get{return Session["SharedInfo"] as string;}
set { Session["SharedInfo"] = value; }
}
//在內容頁中添加好@MasterType VirtualPath
protected void Page_Load(object sender, EventArgs e)
{
Master.SharedInfo = "sharedinfo";
}
protected void btn_submit_Click(object sender, EventArgs e)
{
lb.Text = Master.SharedInfo;
}
引用母版頁的控件:使用Master.FindControl
//在母版頁中設置一個label控件
<asp:Label Text="這是一個用於測試的標簽" Id="lb" runat="server" />
//在內容頁中調用
Label content_lb = (Label)Master.FindControl("lb");
content_lb.Text = "測試成功";
二.嵌套母版頁
說白了就是在次母版頁中,既有對應主母版頁ContentPlaceHolder的Content,也擁有自己為內容頁所留下的ContentPlaceHolder
主母版頁:
Site.master
<%
@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="Site" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>重新過一遍ASP.NET 2.0(C#)</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
次母版頁:
MasterPage/MasterPage.master
<%
@ Master Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="MasterPage.master.cs" Inherits="MasterPage_MasterPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<p>
我是一個嵌套母版頁
</p>
<p>
母版頁中的內容
<asp:DropDownList ID="ddlMaster" runat="server" DataSourceID="XmlDataSource1" DataTextField="text"
DataValueField="value" AutoPostBack="True" OnSelectedIndexChanged="ddlMaster_SelectedIndexChanged">
</asp:DropDownList><asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Config/DropDownListData.xml">
</asp:XmlDataSource>
</p>
<p>
內容頁中的內容
<asp:ContentPlaceHolder ID="cph" runat="Server" />
</p>
</asp:Content>
三.動態編程改變母版頁(Dynamically Changing Master Page)
直接上示例:
void Page_PreInit(Object sender, EventArgs e)
{
//判斷Session不為零時,通過對MasterPageFile屬性進行設置來改變母版頁
if (Session["masterPage"] != null)
MasterPageFile = (string)Session["masterPage"];
}
protected void btn_submit_Click(object sender, EventArgs e)
{
//一個母版頁切換的邏輯控制
if ((string)Session["masterPage"] == "~/MasterPage.master")
{
Session["masterPage"] = "~/MasterPage1.master";
//當改變完Session內容后需要刷新頁面
Response.Redirect(Request.Url.ToString());
//另一種刷新頁面的方式
//Server.Transfer(Request.Path);
}
else
{
Session["masterPage"] = "~/MasterPage.master";
Response.Redirect(Request.Url.ToString());
}
}
