Monday, March 17, 2008

Master Page PreInit Event Work Around

Because master pages are actually user controls, they do not have PerInit event. But this is the only time when you can change the MasterPageFile property. So, what can we do if we have sophisticated hierarchy of master pages and we need to change the master page of some master page within this master page? The only way to do this is to handle PreInit event of the page, find the appropriate master page and change its master page. But if you still want to have the logic which master page should be used runtime within the master page file, here is one solution to do that with reflection. Override page OnPreInit method and write this code:

// simulates PreInit event for Master pages
MasterPage master = Master;
while ( master != null )
{
   MethodInfo mi = master.GetType().GetMethod( "PreInit" );

   if ( mi != null )
   {
      mi.Invoke( master, null );
   }

   master = master.Master;
}

Then, in the .master file which you would like to change its master page runtime, you should define method like this:

<script runat="server" type="text/C#">
public void PreInit()
{
   Account acc = LoggedAccount.GetFromSession( Session );
   MasterPageFile = string.Format( "~/local/en-US/{0}/Main.master", acc.Group );
}
</script>

No comments:

eXTReMe Tracker