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.

This is a simple method to return a style rule to define the background color of the page. I have three rules defined.

public

string

GetBackgroundClass(){

switch

( Request.QueryString[

"bkg"

]) {

case

"1"

:

return

"bkg1"

;

case

"2"

:

return

"bkg2"

;

case

"3"

:

return

"bkg3"

;

default

:

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.

.bkg1

{

background-color

:

#FFFFCC;

}

.bkg2

{

background-color

:

#C30000;

}

.bkg3

{

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:

Red:

Blue:

Share This Article With Your Friends!

Googles Ads Facebook Pixel Bing Pixel LinkedIn Pixel