asp.net中 如何编写代码来引用母版页?

可以在内容页中编写代码来引用母版页中的属性、方法和控件,但这种引用有一定的限制。对于属性和方法的规则是:如果它们在母版页上被声明为公共成员,则可以引用它们。这包括公共属性和公共方法。在引用母版页上的控件时,没有只能引用公共成员的这种限制。

引用母版页上的公共成员

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;

}

}