Choosing the MasterPage through a Dynamic Property

blog header image

Yet another answer to a question I've heard several times: "How do I make it possible for the editor to change the Master Page used for the site." It's easy to image a lot of uses for this (especially in an enterprise environment), and it's actually not that difficult to do. The trick is to hook into the code at the right point in time. Here's a simple step-by-step guide:

1) First of all, you still have to set the MasterPageFile property in your @Page directive. This way Visual Studio will accept that you create asp:content blocks on your markup page (the aspx). Hardcode the MasterPageFile in the @Page directive to the default Master, you want it to fallback to, when a property is not set.

2) Create a Dynamic Property in admin mode of type string, call it for instance "MasterPageFile" (You could also make it as a drop-down list of some  options - that's probably nicer for the editor).

3) In the code behind for your pages, hook into the OnPreInit event and set the MasterPageFile property to get it's input from the CurrentPage["MasterPageFile"]. A better solution is to make a shared page class all your pages inherit from and set it there.  Your code could look like this:

protected override void OnPreInit(EventArgs e)
{
    if (!string.IsNullOrEmpty((string)CurrentPage["MasterPageFile"]))
    {
        this.MasterPageFile = (string)CurrentPage["MasterPageFile"];
    }
    base.OnPreInit(e);
}

4) Now you're all set - just use the set the Dynamic Property and watch the pages change!

Recent posts