C# 如何从内容页检索母版页中的控件

C# 如何从内容页检索母版页中的控件,c#,asp.net,master-pages,C#,Asp.net,Master Pages,最近我问了一个问题,关于如何从内容页检索母版页中的控件。 许多人建议我从我的内容页使用以下代码: Label lbl = this.Master.Page.FindControl("uxLabel") as Label; //Note any server controls defined in the master page could be not be accessible even after a cast is performed, because they could be

最近我问了一个问题,关于如何从内容页检索母版页中的控件。 许多人建议我从我的内容页使用以下代码:

    Label lbl = this.Master.Page.FindControl("uxLabel") as Label;
//Note any server controls defined in the master page could be not be accessible even after a cast is performed, because they could be marked as protected
    <%@ MasterType VirtualPath="~/Templates/WebsiteMasterPage.master" %>
protected void Page_Load(object sender, EventArgs e)
{
    this.Master.HeaderLabel.Text = "Any Text here!";
}
这种方法当然是有效的,我也意识到有一种强类型的解决方案是可用的,它不涉及强制转换主属性

在母版页位置:

public Label HeaderLabel
{
    get { return uxLabel; }
}
在内容页中使用主控类型:

    Label lbl = this.Master.Page.FindControl("uxLabel") as Label;
//Note any server controls defined in the master page could be not be accessible even after a cast is performed, because they could be marked as protected
    <%@ MasterType VirtualPath="~/Templates/WebsiteMasterPage.master" %>
protected void Page_Load(object sender, EventArgs e)
{
    this.Master.HeaderLabel.Text = "Any Text here!";
}
我想知道:

  • 你觉得这个怎么样 方法 还有其他解决办法吗
谢谢你的时间

我的答案是“为什么不呢?

这两种方法对我来说都是很好的方法,但首先需要较少的编码才能开始使用,因为您不需要初始化任何类字段和设计属性。但必须在运行时找到控件

第二种方法,称之为“类型化方法”,只是转换到特定的母版页类,您可以访问任何特定于类的成员

“类型化方法”的主要问题是什么?您需要对类库(程序集)的引用才能访问此类母版页的成员,这在某些情况下是不可取的。例如,您有一个控件库,并且希望访问一个必需的母版页控件,该控件提供使用某个库控件所需的一些行为。您可能需要引用web客户端程序集,但您不能这样做,因为您在web客户端本身中引用了控件库,而这是一个循环引用


工具、方法可在特定场景中使用为什么不?答案可以扩展到如果需要,为什么不使用“类型化方法”,并且您的场景与该概念兼容?

感谢Matias的意见..net可以允许您直接访问控件,但控件被设置为保护模式这是出于安全原因。我想说你们搞砸了安全。MS允许使用MasterType(强类型)进行此操作,所以我看不出你们的断言有什么意义。请告诉我们更多关于你的想法