从内容页获取母版页的引用

 1、  在内容页中核心对象Page具有一个公共属性Master,该属性能够实现对相关母版页基类MasterPage的引用,由此可以用MasterPage实现对母版页各个子对象的访问。通过MasterPage中的FindControl方法便可以实现从内容页获取母版页控件引用。这里的FindControl方法用于根据给定的名称在当前指定的控件容器中查找子控件并返回指定名字的子控件的引用,并且在引用时需要将返回的Object转换为合适的类型。

例: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”对像

  }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值