Dynamic CSS files in ASP.net Master Page using C#

I have a reporting portal that serves up SSRS (SQL Server Reporting Services) reports to users. The users are from different organisations, indicated by a user group. I needed to have the front end personalised for each different organisation. The approach below loads a different CSS file depending on the user group of the logged in user. I’m using a master page solution, so the CSS is loaded in the master page file. The CSS files for each organisation are stored in a CSS folder.

If we look at a standard link to a style sheet that we would place in the head of our master page

<head runat="server">
    <title></title>
    <link href="CSS/StyleSheet.css" type="text/css" rel="stylesheet" />
</head>

We are going to change this to what we see below

<head runat="server">
    <title></title>
    <link id="CurrentStyleSheet" type="text/css" rel="stylesheet" runat="server"/>
</head>

You need to note three things in the above code. We need to ensure that runat=”server” is added, that there is no “href” to point to our CSS file as we be adding this in code, and we have given our link an id.

Firstly lets load the CSS file in the Page_Load event of the master page. We reference the link using its id and add the “href” attribute and value to the link (the !Page.IsPostBack stops this from being done repeatedly on every page postback).

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                CurrentStyleSheet.Attributes.Add("href", "CSS/StyleSheet.css");
            }
        }

This is all good, however we are still just loading one CSS file regardless. In my database I have a field that holds the CSS file name for each user group and a function getCssFile() that returns the CSS file name for the logged in user. (I’m not going to cover how that function reads the value from the database here).

So the code now becomes

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                CurrentStyleSheet.Attributes.Add("href", string.Format("CSS/{0}", getCssFile()));
            }
        }

This goes and gets the name of the style sheet from the database for the logged in user and inserts this into the “href” attribute.

Advertisements
This entry was posted in Programming and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s