如何:引用 ASP.NET 主版頁面的內容 (zz)

來源:互聯網
上載者:User
原文地址:http://msdn2.microsoft.com/zh-cn/library/xxwa0ff0(VS.80).aspxASP.NET  如何:引用 ASP.NET 主版頁面的內容 

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

引用主版頁面上的公用成員
  1. 在內容頁中添加 @ MasterType 指令。在該指令中,將 VirtualPath 屬性設定為主版頁面的位置,如下面的樣本所示:

    <%@ MasterType virtualpath="~/Masters/Master1.master" %>

    此指令使內容頁的 Master 屬性被強型別化。

  2. 編寫代碼,將主版頁面的公用成員用作 Master 屬性的一個成員,如本例中,將主版頁面名為 CompanyName 的公用屬性的值賦給內容頁上的一個文字框:

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

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

    Visual Basic 複製代碼

    Sub Page_Load()    Dim mpContentPlaceHolder As ContentPlaceHolder    Dim mpTextBox As TextBox    mpContentPlaceHolder = _    CType(Master.FindControl("ContentPlaceHolder1"), _    ContentPlaceHolder)    If Not mpContentPlaceHolder Is Nothing Then    mpTextBox = CType(mpContentPlaceHolder. _    FindControl("TextBox1"), TextBox)    If Not mpTextBox Is Nothing Then    mpTextBox.Text = "TextBox found!"    End If    End If    ' Gets a reference to a Label control not in a     ' ContentPlaceHolder    Dim mpLabel As Label    mpLabel = CType(Master.FindControl("masterPageLabel"), Label)    If Not mpLabel Is Nothing Then    Label1.Text = "Master page label = " + mpLabel.Text    End If    End Sub    

     

    C# 複製代碼

    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;    }    }    

請參見概念

ASP.NET 主版頁面概述
以編程方式使用 ASP.NET 主版頁面
其他資源

以編程方式訪問 ASP.NET 控制項

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.