Dynamically change Body Background-image!

What if you need to dynamically change the Body Background-image based on whether the Page IsPostback?  You have a CSS Stylesheet for the page, and that Stylesheet has a background-image defined for the body tag.

So what is the [workaround]?

You first must define the body tag on the page as a server control.  Then you can access the body control via code in your page:

  1: protected void Page_Load(object sender, EventArgs e)
  2: {
  3: 	if (!IsPostBack)
  4:         {
  5:             var rnd = new Random();
  6:             // the background images are incrementally named: background1,png, background2.png, etc.
  7:             // the Random number is seeded with 1 and the maxNum is (the number of background images + 1)
  8:             int rndInt = rnd.Next(1,4);
  9:             string imagePath = String.Format("background-image: url('../../images/background{0}.png')", rndInt);
 10:             // the body tag on the aspx page must be: <body id="body1" runat="server">
 11:             this.body1.Attributes.Add("style", imagePath);
 12:         }
 13:         else
 14:         {
 15:             // this will revert back to the background image defined in the stylesheet    
 16:             this.body1.Attributes.Remove("style");
 17:         }
 18: }

And Voila!  Problem solved!

Print | posted on Sunday, December 13, 2009 5:11 PM


No comments posted yet.

Your comment:


Copyright © intermark

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski