by aherrick
22. December 2008 07:14
Working on a project I need the ability to programmatically change the web application's associated master page (and associated CSS). Most of the pages in the application were content pages (derived from the content page) however some were just static pages. Since there was no MasterPage assoicated with these static pages, dynamically assigning the CSS was the next best option.
I created a BasePage for ALL pages in the application to derive from.
For the ContentPages (pages that point to a MasterPage) I created a method in the BasePage to assign the necessary master page. This method is called in the Page_PreInit method of the content page. See below.
protected void Page_PreInit(object sender, EventArgs e)
{
// set master page
this.SetMasterPage();
}
SetMasterPage is a simple method to dynmically change the MasterPage...
public void SetMasterPage()
{
// change master page
// will return random number between 1-3...
int masterPage = RandomNumber(1, 4);
string fullMaster = ResolveUrl(string.Format("~/Site{0}.master", masterPage));
this.MasterPageFile = fullMaster;
}
Dynamically set the CSS on the static pages in a similar matter. In the code behind of the specific page, , call SetCSS in the Page_Init method. Dynamically setting the CSS is very easy too...
public void SetCSS()
{
// set CSS
// ALL CSS has to be set programatically...
HtmlLink css = new HtmlLink();
int cssNum = RandomNumber(1, 3);
css.Href = ResolveUrl(string.Format("~/StyleSheet{0}.css", cssNum));
css.Attributes["rel"] = "stylesheet";
css.Attributes["type"] = "text/css";
css.Attributes["media"] = "all";
Page.Header.Controls.Add(css);
}
Really that's all there is to it. This code can be tweaked to suit your needs. This gives a lot more flexibility than simply dynamically changing your CSS file.
Attached is the code
ControlMasterPagesProgramatically.zip (34.59 kb)
f41c0785-394e-474b-b011-8d615b7e197f|1|5.0
Tags: