Dynamically Loading Master Pages in ASP.Net: Part 2

Introduction

 

In Part 1 of this article, we have discussed how to load Master Pages Dynamically for one content page but in this part we will discuss how to load for multiple content pages even. Please do read previous part then come to this otherwise you can't understand completely. The easiest way to apply the same logic to multiple content pages is to create a new base Page class. The example given below contains a new Base Page class named DynamicMasterPage. Now we have to add the file given below in our application's App_Code folder. If you create class file at very first time then it will prompt you to create App_Code Folder to place that class file.

 

DynamicMasterPage.vb Class File Code

 
Imports Microsoft.VisualBasic

Public Class DynamicMasterPage
    Inherits Page

    Protected Overrides Sub OnPreInit(ByVal e As EventArgs)
        Me.MasterPageFile = CType(Context.Profile("MasterPageFile"), String)
        MyBase.OnPreInit(e)
    End Sub

End Class

 

Web.config File Code

 
<?xml version="1.0"?>
<configuration>
                <
system.web>
                                <
compilation debug="true" targetFramework="4.0"/>
                </system.web>

  <system.web>

    <pages pageBaseType="DynamicMasterPage" />

    <profile>
      <
properties>
        <
add
          name="MasterPageFile"
          defaultValue="DynamicMaster1.master" />
      </properties>
    </
profile>
  </
system.web>

</configuration>

 

If you register the DynamicMasterPage class as the base Page class, every page in our application automatically inherits from the new base class. Every page inherits the new OnPreInit() method and every page loads a Master Page dynamically. This is pretty cool and used on maximum websites today.

 

Note: This is last part of this article series. 

HAVE A GREAT CODING!