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.