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