1

I have a page in my application where i need to load two css files dynamically based on the user who is logging in.

How can I load two css files in a single page dynamically?

This is my code to generate the css dynamically:

This is my code:

  HtmlLink objCSS = new HtmlLink();
  objCSS.Attributes.Add("href", "Includes/css/ADxMenuEmbed.css");
  objCSS.Attributes.Add("rel", "stylesheet");    
  objCSS.Attributes.Add("type", "text/css");
  Header.Controls.Add(objCSS);

Can anyone provide some ideas or samples to solve this problem?

3
  • Are you using any server side technology? Or just purely html and css? Commented Aug 9, 2010 at 7:08
  • The title says Asp.Net. I'll fix the tags Commented Aug 9, 2010 at 7:10
  • I am using ASP.Net...as my server side technology Commented Aug 9, 2010 at 7:16

2 Answers 2

3

Following is way you can add css file dynamically in you asp.net application

if you want to load file as per user login you have to put if condition on role of use or something that is unique you are using

protected void Page_Init(object sender, EventArgs e)
{

  HtmlLink css = new HtmlLink();
  css.Href = "css/fancyforms.css";
  css.Attributes["rel"] = "stylesheet";
  css.Attributes["type"] = "text/css";
  css.Attributes["media"] = "all";
  Page.Header.Controls.Add(css);
}
Sign up to request clarification or add additional context in comments.

1 Comment

i am using the same code but only one css is applied and not the other one This is my code: HtmlLink objCSS = new HtmlLink(); objCSS.Attributes.Add("href", "Includes/css/ADxMenuEmbed.css"); objCSS.Attributes.Add("rel", "stylesheet"); objCSS.Attributes.Add("type", "text/css"); Header.Controls.Add(objCSS);
2

You can load the sheet in the Code Behind like @June suggests or you can load it in the aspx itself using inline code (frowned upon by some, but since a css file is layout logic I prefer to do it this way)

If you always load the second style sheet, just that you load a different one per user you could write something like this inside the head tag of your aspx page.

 <link href="<%= the name of your style sheet %>" rel="stylesheet" type="text/css" />

if you only put the style sheet in sometimes you can write this

<% if (whatever)
   { %>
    <link href="style.css" rel="stylesheet" type="text/css" />
<%} %>

2 Comments

One small note - if you have <head runat="server"> (which is the default) your example will often throw an exception. Use <%# instead and call the .DataBind() method to avoid it.
Why should this example throw an exception?

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.