RE: Master-Page-Limitation in ASP.NET 2.0

How great is this? It would seem that dynamic master pages are in fact possible. I just wonder what this will do to page performance....

The concept of Masterpages introduced in ASP.NET “Whidbey” is really fascinating. But it seems to have one major limitation, which appears to make it quite unusable in bigger Web-Applications: There seems to be no functionality, which allows a developer to programmatically change the used Master-Page at runtime.

If you think so, you should read this article: http://msdn.microsoft.com/msdnmag/issues/04/06/ASPNET20MasterPages/default.aspx

After reading this, you'll be able to change the MasterPage at runtime using the new PreInit-Event:

protected override void OnPreInit(EventArgs e)
{
  this.MasterPageFile = "OtherTemplate.master";
  base.OnPreInit(e);
}

Protected Overrides Sub OnPreInit(ByVal e As EventArgs)
   Me.MasterPageFile = "OtherTemplate.master"
   MyBase.OnPreInit(e)
End Sub

And after all, the concepts of MasterPages should work. :-)

Thanks to Scott Galloway (http://www.mostlylucid.co.uk) for his hint on this topic.

[Via K Samaschke & Scott Galloway]

5 Comments

  • Humm, I wonder about this:

    If the template contains serer controls, won't changing the materpage change the control tree and thus break viewState?

  • I think you have to think about how you'd have meaningful viewstate at the same time you're changing the master page setting on the PreInit event.



    In order to have any viewstate, the page must have passed through the SaveViewState event, which is after Load and just before Render. SaveViewState is way after PreInit.



    So if you have ViewState in the PreInit event, you must be in a postback. The first question you'd have to ask is, why are you changing the master page during a postback? Let's say you have a good reason, even though I can't think of one.



    If you change the master page in the PreInit, the control tree will indeed be different. When the LoadViewState and LoadPostbackData events fire they probably will not find the data they're looking for.



    Is this a limitation? I don't think so in the real world. Changing the master page during a postback would seem like a mis-application of the design pattern MS is trying to facilitate w/ the Master Page architecture.



    BTW - you can also change Theme programmatically during the PreInit event. I think a good application of this technique is in a commonly inherited base page class that handles both theme and master page.

  • I saw it as most useful during the first time a page loads, to set the template. I imagine if you wanted to give the user control to change the master page, then this may happen as a result of a postback, but I'm not seeing this as a common thing.

  • u must write base.MasterPageFile = "OtherTemplate.master";

  • Also no way to fire an event at least a button click event in the content page.

Comments have been disabled for this content.