Andy's observations as he continues to attempt to know all that is .NET...

Friday, July 07, 2006

Visual Studio and ASP.NET Master Pages

I finally got tierd of the bug in the Visual studio designer for ASP.NET master pages. The issue is this, if you don’t hardcode the master page for the page in the page itself the designer will not see that you are using master pages, even if you define one in the pages section of web.config. This greatly defeats one of the objectives of master pages in that I would like to tweak the master page at deployment time, and the default behavior is page value overrides config file.

Possible solutions are have a default.master page, and make all pages point to that. Then have the actual master pages as separate files and simply copy over the default.master with the one you want at deployment time.

That seems clunky to me, so another option would be to make it use the value in web.config as opposed to the one defined on the page. You can do this by creating a new class that sits between your form and the System.Web.UI.Page class. This class will simply inspect the value held in web.config and if its set override the page setting.

using System;

using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Web.Configuration;

class SiteMaster : Page
protected override void OnPreInit(EventArgs e)
PagesSection pagesSection = (PagesSection) ConfigurationSettings.GetConfig("system.web/pages");

if (pagesSection.MasterPageFile != String.Empty)
this.MasterPageFile = pagesSection.MasterPageFile;




Simply modify your code behind file to look like

public partial class DefaultForm : SiteMaster

And you will now get the master page as defined in the web.config. For pages you want to set by override the site default continue to derive directly from System.Web.UI.Page.

No comments:

About Me

My photo
Im a freelance consultant for .NET based technology. My last real job, was at Cisco System were I was a lead architect for Cisco's identity solutions. I arrived at Cisco via aquisition and prior to that worked in small startups. The startup culture is what appeals to me, and thats why I finally left Cisco after seven years.....I now filll my time through a combination of consultancy and teaching for Developmentor...and working on insane startups that nobody with an ounce of sense would look twice at...