Mike Cole
Mike Cole

Reputation: 14713

ASP.NET - Conditionally link CSS file

I want to conditionally link a CSS file base on the user's Membership role. An administrator should link my admin.css file while everybody else (other roles and anonymous users) should display my global.css file. Can this be done?

Upvotes: 4

Views: 2032

Answers (5)

User
User

Reputation: 30945

If you wish to enable/disable/show/hide controls based on the role this would be nothing more than "security by obscurity" since switching off styles or setting a browser to a specific css file to override what is actually served would easily display all that is secret.

Another issue would be caching. Some browsers like Opera/Firefox happily cache all that is cacheable, so the user will have to click "Reload page". You can probably disable caching but then your css will be downloaded all over again thus unnecessarily consuming traffic.

Upvotes: 0

pmarflee
pmarflee

Reputation: 3428

If you set the head element of your page to run server-side, you can inject a new HtmlGenericControl into the header that represents the link if the user is in a particular role.

Upvotes: 0

Michael Haren
Michael Haren

Reputation: 108246

Try this:

protected void Page_Init(object sender, EventArgs e)
{
    HtmlLink css = new HtmlLink();
    // add conditional logic to add correct css file        
    css.Href = "css/fancyforms.css"; 
    css.Attributes["rel"] = "stylesheet";
    css.Attributes["type"] = "text/css";
    css.Attributes["media"] = "all";
    Page.Header.Controls.Add(css);
}

Upvotes: 8

Chad Birch
Chad Birch

Reputation: 74558

Sure, when you're outputting the <head> section, have an if statement check a session variable that has their "user level", then output the corresponding <link> tag (or @import line, depending how you prefer to do your CSS).

Upvotes: 0

Kirtan
Kirtan

Reputation: 21695

Either you can create theme based on the role - AdminTheme (will contain admin.css) & GlobalTheme (will contain global.css), or else you can dynamically write the <link> element in the <head> tag after giving the runat="Server" attribute to it.

You can then set the page's theme dynamically in the PreInit or Init event based on the role.

Upvotes: 0

Related Questions