例:Master文件中通过Page_Load事件获取当前日期和时间并在母版页中显示出来,代码如下:
using System;
……….
public partial class MasterPage:System.Web.UI.MasterPage
{
protected void Page_Load(object sender,EventArgs e)
{
Label1.Text=System.DateTime.Now.ToString(); //设置Label控件以显示日期和时间
}
}
在内容页中的Button事件:
using System;
……
public partial class Index:System.Web.UI.Page
{
protected void Page_Load(object sender,EventArgs e)
{
}
protected void Button1_Click(object sender,EventArgs e)
{
TextBox1.Text=(Master.FindControl(“Label1”) as Label).Text //通过FindControl方法获取母版页中Label1控件上的数据
}
}
或在内容页中的Page_LoadComplete事件中添加相应的事件:
public partial class MasterPage:System.Web.UI.MasterPage
{
protected void Page_Load(object sender,EventArgs e)
{
}
protected void Page_LoadComplete(object sender,EventArgs e)
{
Label1.Text=(Master.FindControl(“Label1”) as Label).Text;
}
}
2、 通过MasterType指令创建与内容页相关的母版页的强类型的引用,在使用该指令时通过设置VirtualPath属性指定一个与内容页相关的母版页的存储地址。当该内容页创建自己的Master属性时,属性的值即被设置为引用的母版页的存储地址,于是通过MasterType指令就可以创建与内容页相关的母版页的强类型引用。
例:在MasterPage.master.cs文件中定义具有公共属性的Label控件:
using System;
…….
public partial class MasterPage:System.Web.UI.MasterPage
{
protected void Page_Load(object sender,EventArgs e)
{
}
protected Label MasterLabel //定义具有公共属性的Label
{
get
{
return Label1;
}
set
{
Label1=value;
}
}
在内容页Index.aspx文件中的@Page指令的后面添加MasterType指令,指令中的VirtualPath属性用于指定母版页存储地址。
<% MasterType VirtualPath=”~/MasterPage.master” %>
在Index.cs中的Page_Load事件中添加代码:
public partial class Index:System.Web.UI.Page
{
protected void Page_Load(object sender,EventArgs e)
{
Master.MasterLabel.Text=System.DateTime.Now.ToString(); //对MasterLabel要注明是“Master”对像
}
}