子頁調用母版頁屬性方法及控件


子頁調用母版屬性方法及控件

<asp:content id="content1" contentPlaceHolder="body" runat="server">

放置內容

</asp:content>

<asp:contentPlaceHolder id="body" runat="server">

以上是一個放置內容的容器

(1)調用母版中的方法及屬性:在子頁聲明被調用頁的信息,然后直接用master.XXXX()調用。

(2)調用母版中的控件:在子頁中通過FindControl搜索母版頁的id,調用之。 

母版頁.master

<form id="form1" runat="server">

    <asp:Label ID="masterLabel" runat="server" Text="hello,this is a master!"></asp:Label><br />

    <div>

        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">

        </asp:contentplaceholder>

    </div>

</form>

母版頁.aspx.cs(注意為public

    public void SayHello()

    {

        Response.Write("hello,everyone!I am a fresh chicken.");

    }

首先呢,是調用母版方法(調用屬性一樣) 

子頁中的.aspx首部加入如下代碼:

<%@ MasterType VirtualPath="~/母版頁.master" %>

 子頁則直接通過母版的方法名調用:

protected void Page_Load(object sender, EventArgs e)

{

    Master.SayHello();

}

其次,調用母版中的控件(FindControl):

子頁采用FindControl的方法(此處是通過按鈕出發事件而將調用來的母版屬性顯示在Label中)

 protected void btnGetMaster_Click(object sender, EventArgs e)

{

    Label lbMaster = Master.FindControl("masterLabel") as Label;

    if (lbMaster != null)

    {

        Label2.Text = lbMaster.Text.ToString();

    }

}

 其實,母版可以存在多個子版塊的形式,FindControl也將變換為,事實上上面的程序也是這種的簡寫

Label lbMaster = Master.FindControl("ContentPlaceHolder1") .FindControl("Label1") as Label;

母版頁和內容頁的運行過程可以概括為以下5個步驟。
   (1)用戶通過鍵入內容頁的URL來請求某頁。
   (2)獲取內容頁后,讀取@ Page指令。如果該指令引用一個母版頁,則也讀取該母版頁。如果是第一次請求這兩個頁,則兩個頁都要進行編譯。
   (3)母版頁合並到內容頁的控件樹中。
   (4)各個Content控件的內容合並到母版頁中相應的ContentPlaceHolder控件中。
   (5)呈現得到結果頁。
母版頁和內容頁事件順序
(1)母版頁中控件Init事件;
   (2)內容頁中Content控件Init事件;
   (3)母版頁Init事件;
   (4)內容頁Init事件;
   (5)內容頁Load事件;
   (6)母版頁Load事件;
   (7)內容頁中Content控件Load事件;
   (8)內容頁PreRender事件;
   (9)母版頁PreRender事件;
   (10)母版頁控件PreRender事件。
   (11)內容頁中Content控件PreRender事件。
使用母版頁的優點:
    (1)有利於站點修改和維護,降低開發人員的工作強度
    (2)有利於實現頁面布局
    (3)提供一種便於利用的對象模型


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM