MasterPage嵌套及MasterPage中的控件和变量的访问
1. 嵌套母版页(1) 主母版页 MainMasterPage.master
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MainMasterPage.master.cs" Inherits="MainMasterPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> </head> <body leftmargin="0" topmargin="0"> <form id="form1" runat="server"> <div align="center"> <table width="763" height="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td width="763" valign="top"> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </td> </tr> </table> </div> </form> </body> </html> |
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="SubMasterPage.master.cs" MasterPageFile="~/MainMasterPage.master" Inherits="SubMasterPage" %> <asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="server"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="244" valign="bottom"> <img src="images/pagepic.gif" width="244" height="223"> <h1> 以上内容来自子母版页</h1> </td> <td valign="top" align="left"> <asp:ContentPlaceHolder ID="ContentPlaceHolder2" Runat="server"> </asp:ContentPlaceHolder></td> </tr> </table> </asp:content> |
2. 访问母版页控件和属性
(1) 母版页后台代码访问
在母版页前台页面中添加一个服务器控件
<asp:Label ID="LabelInMaster" runat="server"></asp:Label>
然后在母版页的Page_Load事件中写代码
protected void Page_Load(object sender, EventArgs e)
{
LabelInMaster.Text = "现在时间:" + System.DateTime.Now.ToShortTimeString();
}
(2) 在内容页面中调用母版页控件
在母版添加控件和属性
<asp:Label ID="Label1" runat="server"></asp:Label>
public Label MasterPageLabel
{
get
{
return Label1;
}
set
{
Label1 = value;
}
}
先要在内容页面中添加
<%@ MasterType VirtualPath="~/MasterPage22.master" %>
然后后台才能调用
protected void Page_Load(object sender, EventArgs e)
{
Master.MasterPageLabel.Text = "现在时间:" + System.DateTime.Now.ToShortTimeString();
Master.MasterPageLabel.Font.Size = 20;
}
(3) 同上,内容页面设置变量的值(绑定值)
在母版添加绑定标识、变量和属性
<%= LabelText %>
string _labelText = "";
public String LabelText
{
get
{
return _labelText;
}
set
{
_labelText = value;
}
}
同上在内容页面里加上:
<%@ MasterType VirtualPath="~/MasterPage33.master" %>
在后台代码中
protected void Page_Load(object sender, EventArgs e)
{
Master.LabelText = "现在时间:" + System.DateTime.Now.ToShortTimeString();
}