2

I'd like to change the CSS File that's being used at runtime of my ASP.NET Web Application.

Let's say I've got 2 CSS Files, red.css and blue.css.

I've tried the following approach:

In my Master Page, I've got the following link:

<link rel="Stylesheet" ID="Styles" runat="server"/>

In the Master Pages Page_Load:

Styles.Href = Global.CSSPath;

Global.asax:

public static string CSSPath = "red.css"; (assuming its in the same folder)

This approach works. And of course I could easily implement some functionality to change the value of CSSPath and make it blue.css or whatever - now I'd like to know whether this only affects one user or everyone using my web application.

If it only affects one user: Great, thanks! If it doesn't: What should I do to achieve being able to change themes at runtime for a specific user/session?

Thanks,

Dennis

Dennis Röttger
  • 1,975
  • 6
  • 32
  • 51

2 Answers2

3

try adding something like this in your html

    <script runat="server">

    protected void Page_Init(object sender, EventArgs e)
    {   
      HtmlLink csslink = new HtmlLink();
      csslink.Href = "~/red.css";
      csslink.Attributes.Add("rel", "stylesheet");
      csslink.Attributes.Add("type", "text/css");
      Page.Header.Controls.Add(csslink);    
    }
   </script>
huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99
3

It will affect all users as you're reading the value from a static (global) variable.

For changing the theme at runtime you can do it server-side as you are now but you need to pick up the user specific value, maybe from Session.

Darren Lewis
  • 8,338
  • 3
  • 35
  • 55
  • Thanks, that's what I've been looking for! Do you have any specific approach in mind as I cannot access the Session within all methods of Global.asax? – Dennis Röttger Oct 21 '11 at 12:02
  • You've always got the option of using the built in ASP.NET Themes. Alternatively you'll want to provide common behaviour across all pages rather than trying to do this at the global level. We've done this in the past by making each of our pages inherit from a base class that itself derives from System.Web.UI.Page. In here we'd override an appropriate method in the pipeline and set the property in here. Session will be available and as long as all of your WebForms pages inherit from the new base class they'll get this behaviour for "free". Hope that makes sense. – Darren Lewis Oct 21 '11 at 13:13