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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.