Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

html - Dynamic background-image on body (ASP.NET)

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" ? :-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...