在母版页中查找 ContentPlaceHolders
我正在寻找一种动态加载母版页的方法,以便获取其中的 ContentPlaceHolders 集合。
在我可以访问它的控件之前,我希望不必加载页面对象来分配母版页,但如果这是唯一的方法,我会很乐意使用它。这就是我希望它能够工作的方式:
Page page = new Page();
page.MasterPageFile = "~/home.master";
foreach (Control control in page.Master.Controls)
{
if (control.GetType() == typeof(ContentPlaceHolder))
{
// add placeholder id to collection
}
}
但是 page.Master
抛出空引用异常。它似乎仅在页面生命周期中创建实际页面时才加载。
我什至想过在 Page_Init() 上动态更改当前页面的 MasterPageFile,读取所有 ContentPlaceHolders 然后将原始 MasterPageFile 分配回来,但这太可怕了!
有没有办法将母版页加载到独立于实际页面的内存中,以便我可以访问它的属性?
我的最后手段可能会涉及解析 ContentPlaceHolders 的母版页内容,这不是那么优雅,但可能会更快一点。
有人可以帮忙吗?非常感谢。
I'm looking for a way to dynamically load a master page in order to get a collection of ContentPlaceHolders within.
I would prefer not to have to load a page object to assign the master page to before I can access it's controls, but if that's the only way I'll be happy to use it. This is the way I was hoping it would work:
Page page = new Page();
page.MasterPageFile = "~/home.master";
foreach (Control control in page.Master.Controls)
{
if (control.GetType() == typeof(ContentPlaceHolder))
{
// add placeholder id to collection
}
}
But page.Master
throws a null reference exception. It only seems to load at some point when an actual page has been created in the page lifecycle.
I even thought of dynamically changing the current page's MasterPageFile on Page_Init(), reading all ContentPlaceHolders then assigning the original MasterPageFile back, but that would be horrible!
Is there a way to load a master page into memory independent of an actual page so that I can access properties of it?
My final resort will probably involve parsing the master page contents for ContentPlaceHolders instead, which isn't as elegant but might be a bit faster.
Anyone able to help please? Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该能够使用 LoadControl 加载母版页并枚举 Controls 集合。
要查找内容控件,您需要递归搜索控件集合。这是一个快速而肮脏的例子。
以上可以按如下方式使用
You should be able to use LoadControl to load the master page an enumerate the Controls collection.
To find the Content Controls you will need to recursively search the Controls collection. Here is a quick and dirty example.
The above can be used as follows