I went on vacation at the end of July and returned in early August. Life restarted in fits and starts. But somehow I neglected to get this blog started again. Now that five months have passed, I think it is time to begin again. So without further ado...
Had a question on a forum today about how to access the top master page if you are using nested master pages. Seemed like a good time to break out some recursion.
protected MasterPage UltimateMaster(Page ThePage)
{
if (ThePage.Master == null)
{
//no master
return null;
}
else
{
return UltimateMaster(ThePage.Master);
}
}
//this will call itself until it runs out of Master Pages
protected MasterPage UltimateMaster(MasterPage ThePage)
{
MasterPage TheMaster;
if (ThePage.Master == null)
{
TheMaster = ThePage;
}
else
{
TheMaster = UltimateMaster(ThePage.Master);
}
return TheMaster;
}
I'd add these methods to a base web page class, so I can access them from all my pages. Then it is easy to access the ultimate master page at any time...
MasterPage TheUltimateMaster = UltimateMaster(this);
To access any custom properties or methods that have been exposed, the master page needs to be cast to its strong type...
MyUltimateMasterPageType MyMaster = (MyUltimateMasterPageType) TheUltimateMaster;
Then the ultimate master page is ready to be used...
MyMaster.AUsefulMethod("SomethingSomehting");
I haven't had the occasion to use nested master pages, but I thought I'd offer this as an early Christmas present to anyone who does.
Happy Holidays. Merry Christmas!