asp.net中 如何編寫代碼來引用主版頁面

來源:互聯網
上載者:User

可以在內容頁中編寫代碼來引用主版頁面中的屬性、方法和控制項,但這種引用有一定的限制。對於屬性和方法的規則是:如果它們在主版頁面上被聲明為公用成員,則可以引用它們。這包括公用屬性和公用方法。在引用主版頁面上的控制項時,沒有只能引用公用成員的這種限制。

引用主版頁面上的公用成員
1.在內容頁中添加 @ MasterType 指令。在該指令中,將 VirtualPath 屬性設定為主版頁面的位置,如下面的樣本所示:<%@ MasterType virtualpath="~/Masters/Master1.master" %> 此指令使內容頁的 Master 屬性被強型別化。
2.編寫代碼,將主版頁面的公用成員用作 Master 屬性的一個成員,如本例中,將主版頁面名為 CompanyName 的公用屬性的值賦給內容頁上的一個文字框

引用主版頁面上的控制項
使用 FindControl 方法,將 Master 屬性的傳回值用作命名容器。

下面的程式碼範例示範如何使用 FindControl 方法擷取對主版頁面上的兩個控制項的引用(一個 TextBox 控制項和一個 Label 控制項)。因為 TextBox 控制項處在 ContentPlaceHolder 控制項的內部,必須首先擷取對 ContentPlaceHolder 的引用,然後使用其 FindControl 方法來定位 TextBox 控制項。

void Page_Load()
{
    // Gets a reference to a TextBox control inside
    // a ContentPlaceHolder
    ContentPlaceHolder mpContentPlaceHolder;
    TextBox mpTextBox;
    mpContentPlaceHolder =
      (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
    if(mpContentPlaceHolder != null)
    {
        mpTextBox =
            (TextBox) mpContentPlaceHolder.FindControl("TextBox1");
        if(mpTextBox != null)
        {
            mpTextBox.Text = "TextBox found!";
        }
    }
   
    // Gets a reference to a Label control that not in
    // a ContentPlaceHolder
    Label mpLabel = (Label) Master.FindControl("masterPageLabel");
    if(mpLabel != null)
    {
        Label1.Text = "Master page label = " + mpLabel.Text;
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.