Dynamic background-image on body (ASP.NET)

Lars Holdgaard picture Lars Holdgaard · Feb 21, 2011 · Viewed 33.7k times · Source

I have a situation where I have ~10-20 different background images in a folder. When my site loads I need to choose a specific one of these images based upon some values from the database.

I thought about using runat=server on the body tag, and then adding the attributes dynamically on page_load, but everywhere I have read that suggestion people say it is a really bad idea... Also, I tried it, and it didn't work (however didn't debug it too much).

How would one do this "the right way" ? :-)

Answer

Jon P picture Jon P · Feb 21, 2011

You Can Either dynamically add it via a Generic HTML control:

   using System.Web.UI.HtmlControls;


    protected override void OnInit(EventArgs e)
    {
        // Define an Literal control.
        HtmlGenericControl css = new HtmlGenericControl();
        css.TagName = "style";
        css.Attributes.Add("type", "text/css");

        string imageURL = string.Empty;

        //Logic to determin imageURL goes here

        //Update Tag
        css.InnerHtml = @"body{background-image: url(" + imageURL + ");}";


        // Add the Tag to the Head section of the page.
        Page.Header.Controls.Add(css);

        base.OnInit(e);        } 

The other option is to have a publically exposed property from the code-behind

E.g.

public string backgroundImage = "defaultImage.png";

Update this in page init or onload events.

And reference it in the aspx file either in the head:

<style type="text/css">
    body 
    { 
       background-image:url(<%=backgroundImage%>);
    }
 </style>

or as an attribute of the body tag

 <body style="background-image: url(<%= backgroundImage %>)">

Either of these should be able to help you out.