Dynamically Setting a Style at Run-Time in ASP.NET

Trolling the ASP.NET forums this week I came across a good question, “setting the background on a master page div at run-time?”. Even though the person posted he found an acceptable solution before I posted my response, I think the user has a complicated solution. Mostly because he is using themes, but nonetheless. I posted my answer and thought I would share it here.

A nice feature of CSS is the ability to assign multiple classes to can DOM element via the class attribute. This opens up the possibility to dynamically set a class assignment based on some logic as the page is being rendered. The example below demonstrates having a common style rule and a rule added at run-time. Of course you are not limited to this methodology, there are many ways to apply styles to an element.

<div class="contentBox bkg1">...</div>

I find the easiest way to set something like a dynamic style at run-time is to define a public method in the page class to return the desired rule. For my demonstration I will return a style rule name based on a QueryString parameter, but you can use all sorts of criteria. I also chose to apply the rule to the Body tag.

public string GetBackgroundClass()
    switch ( Request.QueryString["bkg"])
        case "1":
            return "bkg1";
        case "2":
            return "bkg2";
        case "3":
            return "bkg3";
            return "bkg1";

The style rules just set the color as follows, a nice egg shell (at least that is what I call it), red and blue.

    background-color: #FFFFCC;

    background-color: #C30000;

    background-color: #0000CC;

Finally I just inline the call to the method in the HTML markup:

<body class="<%=GetBackgroundClass() %>">

The result as I pass in different values to the page:

Egg Shell:



  1. No trackbacks yet.

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: