spirit_seller
spirit_seller

Reputation: 31

asp.net C# how to programmatically change body background-image on Page_Load

I'm trying to make simple webpage here is my body in HTML code

  <body runat="server" id="BodyTag" style="height: 1171px; width: 1148px;">
        <form id="form1" runat="server">

On Page_Load in my Form.aspx.cs file i want to generate random number from 1 to X where X is the number of files in a specific folder(folder containing images) then i want the body background image to be this random generated number as long as the image names in the folder are 1,2, ... , ... Here is my code

protected void Page_Load(object sender, EventArgs e)
        {
            string path = "C:/Users/FluksikartoN/documents/visual studio 2012/Projects/FLUKSIKARTON/FLUKSIKARTON/WebPhotos/BackGroundPhotos";
            int countF = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length;
           Random rand = new Random((int)DateTime.Now.Ticks);
            int n = rand.Next(1, countF);
            BodyTag.Style["background-image"] = "C:/Users/FluksikartoN/documents/visual studio 2012/Projects/FLUKSIKARTON/FLUKSIKARTON/WebPhotos/BackGroundPhotos/" + n.ToString() + ".jpg";



        }

body background image does not change, it stays white and i dont understand why.Please do not hesitate to ask more information if you need

Upvotes: 1

Views: 6723

Answers (2)

codingbiz
codingbiz

Reputation: 26386

This is better achieved with css. Since you need a way to do it from code, the easiest option that comes to my mind is do it with generated Javascript

Javascript

 <script type="text/javascript">
     document.body.style.background = "url('http://localhost:53942/images/_65209699_fanbase_bbc.jpg')";
     document.body.style.backgroundRepeat = 'no-repeat';
 </script>

Applying it to your code

protected void Page_Load(object sender, EventArgs e)
{
    string script = "<script type=\"text/javascript\">
             document.body.style.background = \"url('http://localhost:53942/images/_65209699_fanbase_bbc.jpg')";
             document.body.style.backgroundRepeat = 'no-repeat';
         </script>\";

    ClientScript.RegisterClientScriptBlock(this.GetType(), "background-changer-script", script);
}

This will just spill the Javascript to the bottom of your page and will be executed by the browser, changing the background as expected. Check the intellisense for Javascript and CSS for other background properties that can be set

Upvotes: 2

Daniel Flippance
Daniel Flippance

Reputation: 7932

You likely need to use a web relative URL:

BodyTag.Style["background-image"] = "http://localhost/FLUKSIKARTON/WebPhotos/BackGroundPhotos/" + n.ToString() + ".jpg";

Another approach would be to provide 1 CSS class per image and then switch which is being used:

CSS

.image1 {
    background-image: url('/FLUKSIKARTON/WebPhotos/BackGroundPhotos/1.jpeg');
}

C#

BodyTag.CssClass = string.Format("image{0}.jpeg", n);

Upvotes: 0

Related Questions