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?
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.
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).
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);
}
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.
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.