OdeToCode IC Logo

Dynamically assign a Style Sheet to an ASP.NET page

Sunday, January 11, 2004
One popular personalization feature is to allow users to select a “skin” for your site (the new MSN home page has some nice looking color schemes to choose from). While ASP.NET server controls allow you to assign a style sheet class easily (the Class property), there is no property or method to set the stylesheet (or stylesheets) assigned to a page.

One easy way to do this is to replace your LINK tag in the ASPX with a Literal server control. The Literal control is a placeholder for rendering text into the HTML. By assigning your LINK tag to the Text property of a Literal, you manage the style sheet of a page from the code behind.

Here is an example ASPX file


<%@ Page language="c#" Codebehind="DynamicStyleSheet.aspx.cs"
 AutoEventWireup="false" Inherits="aspnet.DynamicStyleSheet" %
>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
	<HEAD>
		<title>DynamicStyleSheet</title>
		<asp:Literal id="StyleSheet" runat="Server" />
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server">
			<h6>hello world</h6>
		</form>
	</body>
</HTML>


The corresponding code behind file


public class DynamicStyleSheet : System.Web.UI.Page
{
   protected System.Web.UI.WebControls.Literal StyleSheet;

   private void Page_Load(object sender, System.EventArgs e)
   {
      if(!IsPostBack)
      {
         const string styleFormat = 
           "<LINK href='\"{0}\"' type='\"text/css\"' rel='\"stylesheet\"'>";

         string linkText;
         linkText = String.Format(styleFormat, StyleSheetPath);
         StyleSheet.Text = linkText;         
      }
   }

   protected string StyleSheetPath
   {
      get
      {
         // pull the stylesheet name from a database or xml file...
         return ApplicationPath + "MyStyle.css";
      }
   }

   private string ApplicationPath
   {
      get
      {
         string result = Request.ApplicationPath;
         if(!result.EndsWith("/"))
         {
            result += "/";
         }
         return result;
      }
   }
}