RSS 2.0 Feed
RSS 2.0


Atom 1.0 Feed
Atom 1.0

  Dynamically Loading Master Pages in ASP.NET 2.0 


One of the cool new things introduced in ASP.NET 2.0 is Master Pages. Master Pages give you the ability to define a master page layout and look that is used throughout a site to give a consistent look & feel to all pages. Any updates or changes to the look & feel of the site is done in only one place - the Master Page. Something that might be useful is the ability to dynamically load a master page at runtime, for example based on user preferences or to implement a simple skinning ability for a site framework that might host multiple different sites (something like .Text). It is not a difficult task and can be done very generically to make for easy reuse.

The master page can be selected for a page easily at design-time, I won't focus on that here. But assigning a master page at run-time can only be done in the OnPreInit event since the rendering of the page with the master page occurs prior to the Init event. However, in the case where you want to load the master page dynamically, for example from a database entry based on a user's preference or something, you don't want to add code to the OnPreInit event on every page in the site. It is easy enough to add that code to a base page class that you can inherit from for you pages in the site.

public class DynamicPage : System.Web.UI.Page
{
    protected override void OnPreInit(EventArgs e)
    {
        string masterfile = getMasterPageFromDatabase();
        if (!masterfile.Equals(string.Empty))
        {
            base.MasterPageFile = masterfile;
        }
        base.OnPreInit(e);
    }
}

Now, all you have to do is inherit from that class for all the pages in the site. But this is where it gets even cooler. I posted before about some cool changes for the web.config file in ASP.NET 2.0. So now, you don't even have to change each page class in your web application to inherit from our new DynamicPage class. You can just add it into the web.config and all pages will automatically inherit from it. Doesn't matter if it is a page in the project that you have already, or a new page you add later, it will know to inherit from the DynamicPage class. You add the following to the web.config:

<system.web>
    <pages pageBaseType="DynamicPage" />
    <!-- ...rest of system.web items... -->
</system.web>

Make sure to include the fully-qualified name, including namespace(s) if appropriate, but that is it. I did a quick test and threw a couple of master pages together to test it out. I also added a property to my DynamicPage class to allow for setting the master page file at runtime from a page that inherits from the class and I added a dropdown to allow the master page to be selected by the user. The property I added just stores the master page file name and reloads the current page so the PreInit would fire again, nothing too fancy. Here's some quick images of the pages with the different master pages applied to it (as selected by the user at run-time)

       

Gives a quasi-skinning feel to the site, none of the content pages need to change - and took me all of about 5 minutes to do. All you need to do is implement separate master pages for each look - which is brain-dead easy. I didn't make my master pages anything fancy at all, but changed enough to demonstrate a different look and layout for each master. Don't forget that this does not replace other good design habits, you can still implement the parts that make up the master page as user controls so you're not building things more than once. You can use this same idea with ASP.NET 2.0 themes to load themes for controls at run-time also.

Edit

My take on master pages is that they are very cool and will be a huge benefit to have in ASP.NET 2.0. That said, I do still plan on implementing traditional skinning for most of my own sites & frameworks. I like skinning and having the real granular level control for everything on the page/site. Master pages will be great for a quicker implementation or where simpler requirements permit. I still love regular web application skinning.




                   



Leave a comment below.

Comments

  1. Gerard 5/2/2005 9:13 AM
    Gravatar
    Hi Ryan, like your article. Any ideas how to do the following using MasterPages: have virtual pages, eg: www.somesite.com/about.aspx, where about.aspx doesn't actually physically exist. Content for About.aspx is stored in DB and is inserted into master page template. I'd like to be able to do this for a site I am creating. Any ideas? Thanks, Gerard.
    email: gerard@thewebhouse.co.uk
  2. Ryan Farley 5/2/2005 9:23 AM
    Gravatar
    Gerard,

    To do that, it really has nothing to do with master pages. What you need to do is implement Url ReWriting and map .* to the ASP.NET process. I've been thinking of putting together an article on the subject, but for now, if you do some searches for Url ReWriting you are bound to find something useful on the subject.

    -Ryan
  3. sunilbabu chimata 6/23/2005 11:24 PM
    Gravatar
    Nice article Ryan. It Helped me. Thank you.
    -Bobsunny

    email:sunilhcu@yahoo.com
  4. Samuel Sirois 7/11/2005 11:22 AM
    Gravatar
    Very good article, but what about nested Master Pages? If master pages are stored in the DB, do you believe I should build the master page string by fetching the parents myself in the DB or do you think/know of a better way to achieve this "dynamically loading nested master pages"?

    Thank you!

    Samuel (ssirois <at> logiweb.ca)
  5. Samuel Sirois 7/11/2005 12:25 PM
    Gravatar
    Oops... I do believe I’ve misunderstood the way master pages were dynamically loaded. I thought at first that it was the complete master page that was fetched from the DB but after a few more readings on the Web, I realized that it was only the filePath!

    Do you believe such a thing is possible: having nested Master Pages without physically having them in a file? Is that what you were meaning by "URL reWriting" ?

    Thank you again for your time!


    Samuel (ssirois <at> logiweb.ca)
  6. Ryan Farley 7/18/2005 2:10 PM
    Gravatar
    Samuel,

    Nothing at all has to be in a database, I used that for this example, but it doesn't really have anything to do with master pages. UrlRewriting is something completely different as well.

    A master page is implemented as a file with a ".master" extension and can be set as the master for a given aspx page file. For this example I was simplifying that the name & path of the .master file was stored in a database. Does that make sense?

    -Ryan
  7. Clinton Gallagher 8/7/2005 7:06 PM
    Gravatar
    Such a well done presentation on a timely topic and no project or source all bundled up for download?
  8. Clinton Gallagher 8/28/2005 6:34 PM
    Gravatar
    After testing my methods in a newly created base class I then tried to use the pageBaseType attribute which would not function as documented by Ryan. I searched the web for information about the pageBaseType attribute and found a forum topic claiming this attribute only functions when writing code embedded in the head of the .aspx page.

    That is contrary to Ryan's statements but where could I have possibly gone wrong after verifying the base class and its methods when using the partial class code-behind model?


  9. 阿力 9/27/2005 3:49 AM
    Gravatar
  10. Marlon 10/28/2005 7:56 AM
    Gravatar
    Can I change a master page if it is a nested master page? How can i do this?

    Thanks.
  11. Jordan 12/28/2005 7:41 PM
    Gravatar
    Great example. I'm using this technique to try and run two sites off the same code base and changing the master page based on the URL. This worked fine until I created a stand alone page that will be used in a popup and doesn't use a master page. Because of have the pageBaseType set in the web.config file it's generating a compilation error. If I remove the pageBaseType everything works correctly except for pages without a codebehind file. The error I got was "error CS0030: Cannot convert type 'ASP.signguestbook_aspx' to 'DynamicPage'" According to the online help, pageBaseType should be overriden by the inherits attribute in a stand-alone file, but that doesn't seem to be the case.

    Any idea how to work around this?
  12. Jordan 12/28/2005 7:53 PM
    Gravatar
    I just found the solution to my problem. Adding CodeFileBaseClass="System.Web.UI.Page" to the @Page directive resolved the issue.
  13. Irfan 5/4/2006 4:01 AM
    Gravatar
    Hi

    Out of four masterpages, I can access my two masterpages but rest two i am not able to access.... Browser gets hangs...

    plz help
  14. Irfan 5/4/2006 5:18 AM
    Gravatar
    My Problem Solved...

    you know what was the problem??

    i removed <SPAN> and <DIV> tag.... now the rest of the two pages are working...


    ha..ha...
  15. Wayne Atherton 6/9/2006 4:05 AM
    Gravatar
    Great example but a quick q if I may.

    part of my base page (PageSetup) builds the head, form, body etc tags on the file, within my master page I use a Treeview that needs to be in a form, if I remove the form tags from my master page then the tree view does not work, how can I load the form,body,html tags dynamically in a master page
  16. rcrish 8/10/2006 4:35 AM
    Gravatar
    Hi,

    I am quiet impressed with your articles on .Net. I was going through the other article you redirected from forums relating to window.onload() event.

    I have got a similiar issue dealing with popup in Master page.

    <asp:Content ......>

    <atlas:ScriptManager>
    <Scripts>
    <atlas:ScriptReference ScriptName="AtlasUIDragDrop" />
    <atlas:ScriptReference ScriptName="AtlasUIGlitz" />
    </Scripts>

    </atlas:ScriptManager>
    <table>
    <tr>
    <td>
    <div style="width:276px; height:52px; border:solid 1px black">

    <button id="MyButton" onclick="PopupBehavr.show();" onload="PopupBehavr.show();">Click Me</button>
    </div>
    </td>
    <td width="150px">

    <div id="divPopup" style="position:absolute;display:none;border:1px solid #67CEE7; background-color:White; position:static;">
    <div id="divTitleBar" class="labelboldblue" style="height: 18px;" >Information</div>
    <table>
    <tr>
    <td>
    Different Rates may apply during the stay. <br />Please check multiple rates screen to verify<br />
    </td>
    </tr>
    <tr>
    <td align="center">
    <button id="BtnClose" onclick="PopupBehavr.hide();" style="text-align:center; height:20px; font-size:small;">Close</button><%--</asp:Panel>--%>

    </td>
    </tr>
    </table>
    </div>
    </td>
    </tr>

    </table></div>
    </content>

    Iam testing script for both onclick and onload events of MyButton. both events work well without using master page. but onload event fails to appear the popup when i use master page.
    My script is as follows:


    var PopupBehavr;

    var MyPopup;


    function pageLoad()
    {


    MyPopup = new Sys.UI.Control($("divPopup"));
    MyPopup.initialize();
    var b = MyPopup.get_behaviors()
    PopupBehavr = new Sys.UI.PopupBehavior();

    b.add(PopupBehavr);
    // PopupBehavr.set_y(100);
    // PopupBehavr.set_x(100);


    PopupBehavr.initialize();
    }

    please through some light on the issue and help be solve the issue asap.

    thanks in advance..
  17. Tony 9/14/2006 7:42 AM
    Gravatar
    I wondered if anyone knows how to have a single MasterPage that will work accross different applications; so when updating the masterpage the changes will apply accross all applications?
  18. Tom 12/14/2006 6:41 AM
    Gravatar

    Tony, I don't believe you can have a master page shared amongst applications.
  19. andrew boudreau 1/22/2007 3:47 PM
    Gravatar
    hi guyes, i'm trying to change masterpage on postback by parsing __eventtarget by hand. Is there anyway to get around the viewstate issue that comes up?

    thanks
  20. Greg 4/9/2007 10:53 AM
    Gravatar
    Any thoughts on how to implement this for an application that receives different URLs?

    For example, if a.com, b.com, and c.com are all host headers for myapp.com, I want to load the correct masterpage in based on the requested URL.

    Thanks,
    Greg
  21. Greg 4/9/2007 10:56 AM
    Gravatar
    Update to above... I don't actually want to change the masterpage. I want to change the page theme. Is that much different?

    Thanks,
    Greg
  22. Gravatar
    I have recently been trying to develop an “HttpHandler” that will change the “Master Page” for the portal
  23. Ron Cicotte 12/12/2007 3:09 AM
    Gravatar
    When I tried this I get the following error:

    Cannot convert type 'ASP.login_aspx' to 'OAM.OAM_Code.DynamicPage'
  24. Mert 2/1/2008 4:20 AM
    Gravatar
    thanks ryan good write
  25. Riddhi 2/28/2008 3:20 AM
    Gravatar
    hi my proble me is i am using url writting and when i select on any of the category it would be http://www.webdatadesign.com.au/webp/request.aspx and it wont load image properly any hepl!!
  26. Keith 3/19/2008 8:12 PM
    Gravatar
    Hello,

    I am unable to get this approach to work when using nested master pages, where the main master page is the one dynamically loaded.

    The sub master page seem to be ignored and I get an error message indicating that the ContentPlaceHolder (the one I placed in the sub master page) cannot be found in the main master page.

    Any ideas would be appreciated.

    Keith
  27. Mark 4/19/2008 3:09 PM
    Gravatar
    i cant get this to work, it just assigns the master page that is referenced in the page, not the one assigned in the class.

    any idea what im doing wrong?
  28. Brian 6/11/2008 9:29 AM
    Gravatar
    Using pageBaseType in web config was not having the desired effect across all my .aspx code behind files, because they all already inherit from System.Web.UI.Page. It seems that I still have to go to each .aspx code behind and replace System.Web.UI.Page with my custom base page.

    pageBaseType Specifies the base to use when the pages are stand-alone only. This is overridden by the inherits attribute in a stand-alone file.

    The default is "System.Web.UI.Page".
  29. Srihari 10/7/2008 9:09 AM
    Gravatar
    Thanks Ryan. This was very useful
  30. Moe 1/16/2009 5:19 PM
    Gravatar
    won't if (!masterfile.Equals(string.Empty))
    throw an exception if masterfile == null?

    ------------------------------------
    things that make ya go, hummmmmmmmm....
    -Arsenio Hall
  31. 1/20/2009 12:18 PM
    Gravatar
    pageBaseType | hilpers
  32. 1/21/2009 10:43 AM
    Gravatar
    eventi page in default.aspx | hilpers
  33. 1/21/2009 10:10 PM
    Gravatar
    Master pages | keyongtech
  34. Santhosh 4/7/2010 1:51 AM
    Gravatar
    Article looks good however <pages pageBaseType="DynamicPage" />
    attribute works only for pages which are not having code-behind files.

    Im looking for a solution to share single Master Page across multiple applications.If there is any change in the master page other applications should be transparent.In other words I do not want to re-compile any of my applications to include the master page changes.

    If anybody is having solution pls mail me @ skizhuth@in.ibm.com

    Thanks in advance.

    Cheers
    Santhosh
  35. 7/3/2014 10:45 AM
    Gravatar
    [RESOLVED]Content controls have to be top-level controls in a content page or a nested master page that references a master page. | ASP Questions &amp;amp; Answers
  36. 7/3/2014 7:19 PM
    Gravatar
    [RESOLVED]Set Dynamic Master Page through Dropdown | ASP Questions &amp;amp; Answers
  37. 7/5/2014 8:59 AM
    Gravatar
    [RESOLVED]Changing the Master Page during post back | ASP Questions &amp;amp; Answers
  38. 7/5/2014 2:03 PM
    Gravatar
    [RESOLVED]how to set a dynamically master page | ASP Questions &amp;amp; Answers
  39. 7/5/2014 7:21 PM
    Gravatar
    [RESOLVED]Content controls have to be top-level controls in a content page or a nested master page that references a master page. | ASP Web Form Data Control
  40. 7/6/2014 8:00 AM
    Gravatar
    [RESOLVED]dynamically load master page in .aspx page | ASP Questions &amp;amp; Answers
  41. 7/6/2014 9:49 AM
    Gravatar
    [RESOLVED]Set Dynamic Master Page through Dropdown | ASP Web Form Data Control
  42. 7/6/2014 3:58 PM
    Gravatar
    [RESOLVED]How to change master page to Master page in asp.net | ASP Questions &amp;amp; Answers
  43. 8/31/2016 6:00 AM
    Gravatar
    How To Add Master Pages Dynamically | Information
Comments have been closed on this topic.



 

News


Also see my CRM Developer blog

Connect:              


Sponsor

Sections