放在 master page 上面的控制項,其對應的變數會宣告在 ASP.NET 動態產生的 partial class 裡面,而且它的成員存取範圍是 protected。由於 content page 和 master page 並非繼承關係,因此無法直接在 content page 裡面存取 master page 上面的控制項。

常見的解決辦法是在 master page 類別裡面定義一個公開屬性,將 content page 需要存取的控制項公佈給外界。例如:

public partial class MyMasterPage : System.Web.UI.MasterPage
{
    public string TextValue
    {
        get
        {
            return TextBox1.Text;
        }
        set
        {
            TextBox1.Text = value;
        }
    }
}

然後在 content page 裡面透過 MasterPage 屬性取得 master page 的 instance,就可以存取它的屬性了。如下:

((MyMasterPage) this.Master).TextValue = "Hello!";

上面的用法還要轉型,因為網頁的 Master 屬性的型別是 MasterPage。若嫌麻煩,可以讓網頁使用強型別的 Master 屬性。做法是在 .aspx 網頁中加上一行 @MasterType 指示詞,如下:

<%@ MasterType TypeName="MyMasterPage" %>

或者也可以這樣寫:

<%@ MasterType VirtualPath="~/MyMasterPage.master" %>

但是注意 TypeName 和 VirtualPath 不可同時使用,否則網頁會編譯失敗。

加上 @MasterType 之後,重新編譯專案,然後在 content page 的 code-behind 程式碼裡面就可以這樣寫:

this.Master.TextValue = "Hello";

在寫程式的時候,編輯器的 Intellisense 功能也會知道 Master 屬性的正確型別,挺方便的。