【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

次母版页:

MasterPage/MasterPage.master

</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());
        }
    }

  

 

Site.master

次母版页:

MasterPage/MasterPage.master

</asp:Content>

相关文章:

  • 2022-12-23
  • 2021-11-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-07
  • 2021-10-08
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
  • 2021-11-29
  • 2021-11-04
  • 2022-01-15
相关资源
相似解决方案