Dennis Röttger
Dennis Röttger

Reputation: 1985

Change CSS File (Theme) at runtime (ASP.NET)

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

Upvotes: 2

Views: 5976

Answers (2)

Darren Lewis
Darren Lewis

Reputation: 8488

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.

Upvotes: 3

huMpty duMpty
huMpty duMpty

Reputation: 14460

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>

Upvotes: 3

Related Questions