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!";
}
我想知道:
- 你觉得这个怎么样 方法 还有其他解决办法吗
工具、方法可在特定场景中使用为什么不?答案可以扩展到如果需要,为什么不使用“类型化方法”,并且您的场景与该概念兼容?感谢Matias的意见..net可以允许您直接访问控件,但控件被设置为保护模式这是出于安全原因。我想说你们搞砸了安全。MS允许使用MasterType(强类型)进行此操作,所以我看不出你们的断言有什么意义。请告诉我们更多关于你的想法