Saturday, February 2, 2008

ASP.NET 2.0 Dynamic master page switching

I've been delving into master pages this week and found some really neat features that alot of people often ask for. This I think is one of them. In the next three steps I show you how to allow the user to switch masterpages. Basically the idea hinges on the fact that the masterpagefile property of a page can be switched at runtime, but it has to be done in the preinit event of the form with the content. The users selection can be stored in any session management storage. So here are the steps:

  • Create two or more master pages with the same ContentPlaceHolder controls and public properties. These could be straight copies or better still two child masters based on the same masterfile
  • Optionally, provide a way for users to switch between master pages.

Session("masterpage") = "Master2.master"


Assign the master page in the content page’s Page_PreInit method.

Sub Page_PreInit(ByVal sender As Object, ByVal e _ As EventArgs)

If Not (Session("masterpage") Is Nothing) Then

MasterPageFile = CType(Session"masterpage") ,String)

End If

End Sub

No comments: