身体上的动态背景图片(ASP.NET) [英] Dynamic background-image on body (ASP.NET)
问题描述
我有一个情况我有一个文件夹中〜10-20个不同的背景图像。当我的网站加载我需要选择基于从数据库中的一些值这些图像的特定之一。
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.
我想过使用的 RUNAT =服务器的在身上的标签,然后在Page_Load中动态地添加属性,却处处我已阅读,建议人们说,这是一个非常糟糕的主意......
另外,我试了一下,也没有工作(但是没有调试太多)。
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" ? :-)
推荐答案
您可以动态地通过一个通用的HTML控件添加:
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); }
另一种选择是让从$ C $一个公开暴露的财产C-背后
The other option is to have a publically exposed property from the code-behind
例如
public string backgroundImage = "defaultImage.png";
在页面初始化或onload事件的事件更新此。
Update this in page init or onload events.
和引用它在aspx文件无论是在头部:
And reference it in the aspx file either in the head:
<style type="text/css">
body
{
background-image:url(<%=backgroundImage%>);
}
</style>
或body标签的属性。
or as an attribute of the body tag
<body style="background-image: url(<%= backgroundImage %>)">
无论这些应该能够帮助你。
Either of these should be able to help you out.
这篇关于身体上的动态背景图片(ASP.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!