身体上的动态背景图像 (ASP.NET)

发布于 2024-10-18 04:17:47 字数 237 浏览 6 评论 0原文

我遇到过这样的情况:一个文件夹中有大约 10-20 个不同的背景图像。当我的网站加载时,我需要根据数据库中的某些值选择这些图像中的特定一张。

我考虑过在 body 标签上使用 runat=server ,然后在 page_load 上动态添加属性,但我到处都读到了这个建议,人们说这是一个非常糟糕的主意...... 另外,我尝试了一下,它不起作用(但是没有调试太多)。

如何以“正确的方式”做到这一点? :-)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

花开浅夏 2024-10-25 04:17:47

您可以通过通用 HTML 控件动态添加它:

   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);        } 

另一个选项是从代码隐藏中公开公开属性,

例如

public string backgroundImage = "defaultImage.png";

在页面初始化或 onload 事件中更新此内容。

并在 aspx 文件的 head: 中引用它

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

,或者作为 body 标记的属性

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

,其中任何一个都应该能够帮助您。

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.

鹊巢 2024-10-25 04:17:47

一种方法是拥有这样的属性(也可以使用方法):

    protected string BodyBackgroundImageUrl
    {
        get
        {
            // I just chose random pic
            return "http://www.google.com/images/logos/ps_logo2.png";
        }
    }

您不必设置这样的值,您可以稍后从页面 Init 事件中填充它。

然后在正文中你可以做类似的事情:

    <body style='background:url(<%= BodyBackgroundImageUrl %>) no-repeat;'>

不重复只是为了表明你可以在周围写任何你想要的东西。

当然,您甚至可以有更多的控制权和不同的方式:

    public string GetBodyStyle()
    {
        // Get the picture somehow dynamically
        string bodyBackgroundImageUrl = GetBodyBackgroundImageUrl();

        // You can use StringBuilder or so, not the main point
        var styles = "";

        styles += string.Format("background:url({0}) no-repeat;", bodyBackgroundImageUrl);

        // ... Add some extra styles if you want ...

        return styles;
    }

然后您的 Body 标记将如下所示:

   <body style='<%= GetBodyStyle() %>'>

...

此外,您始终可以使用隐藏字段,您可以从页面中分配值,然后在浏览器中设置JavaScript 到该隐藏字段的后台 URL。

示例(使用 jQuery,但您不必这样做):

$(function() {
   // ASP.NET will fill the ID, then # with ID will show to JS as one JS string
   var myHiddenField = $('#<%= myServerSideHiddenField.ClientID %>');
   var bodyBackground = "url(" + myHiddenField.val() + ")";
   document.body.css("background" , bodyBackground);
});

One way you can do it is have a property like this (a method will also work):

    protected string BodyBackgroundImageUrl
    {
        get
        {
            // I just chose random pic
            return "http://www.google.com/images/logos/ps_logo2.png";
        }
    }

You don't have to set the value like this, you can fill it later from page Init event.

Then in the body you can do something like:

    <body style='background:url(<%= BodyBackgroundImageUrl %>) no-repeat;'>

The no-repeat is just to show you can write whatever you want all around.

Of course you can even have more control, and different ways of things:

    public string GetBodyStyle()
    {
        // Get the picture somehow dynamically
        string bodyBackgroundImageUrl = GetBodyBackgroundImageUrl();

        // You can use StringBuilder or so, not the main point
        var styles = "";

        styles += string.Format("background:url({0}) no-repeat;", bodyBackgroundImageUrl);

        // ... Add some extra styles if you want ...

        return styles;
    }

And then your Body tag will look like:

   <body style='<%= GetBodyStyle() %>'>

...

Also, you can always use a hidden field that you assign the value from the page, and then in browser set the background URL to that hidden field by JavaScript.

Example (using jQuery, but you don't have to) :

$(function() {
   // ASP.NET will fill the ID, then # with ID will show to JS as one JS string
   var myHiddenField = $('#<%= myServerSideHiddenField.ClientID %>');
   var bodyBackground = "url(" + myHiddenField.val() + ")";
   document.body.css("background" , bodyBackground);
});
爱已欠费 2024-10-25 04:17:47

我们一直都是这样做的。

<body runat="server" id="PageBody">

代码隐藏

PageBody.Style.Add("background-color", "" + returncolor + "");

This is how we have been doing it.

<body runat="server" id="PageBody">

code behind

PageBody.Style.Add("background-color", "" + returncolor + "");
梦归所梦 2024-10-25 04:17:47

我正在使用母版页,并从一些建议中获取提示和技巧,我想出了迄今为止最好、最完整的解决方案:

请添加此使用:

using System.Web.UI.HtmlControls;

母版页内部:

<body runat="server" id="masterPageBody">

在任何代码隐藏页面函数中(例如,“Page_Load”):

HtmlControl masterPageBody =(HtmlControl)Master.FindControl("masterPageBody");
masterPageBody.Style.Remove("background-image");
masterPageBody.Style.Add("background-image", "/images/blah.jpg");

I am using a master page, and taking hints and tips from a few suggestions, I have come up with this as the best, and fullest, solution so far:

Please add this Using:

using System.Web.UI.HtmlControls;

Inside the MasterPage:

<body runat="server" id="masterPageBody">

In any code-behind page function (for example, "Page_Load"):

HtmlControl masterPageBody =(HtmlControl)Master.FindControl("masterPageBody");
masterPageBody.Style.Remove("background-image");
masterPageBody.Style.Add("background-image", "/images/blah.jpg");
何以心动 2024-10-25 04:17:47
        serverPath = Request.PhysicalApplicationPath;
        string chosenMap = dropdownlistMap.SelectedItem.Text;

        Bitmap bm = new Bitmap(serverPath + chosenMap);
        int imageWidth = bm.Width;
        int imageHeight = bm.Height;
        bm.Dispose();

        FileInfo fi = new FileInfo(chosenMap);
        string imageSrc = "~/" + fi.Name;

        imgPanel.BackImageUrl = imageSrc;
        imgPanel.Width = imageWidth + 4;
        imgPanel.Height = imageHeight + 4;
        imgPanel.BorderColor = Color.Yellow;
        imgPanel.BorderStyle = BorderStyle.Groove;
        imgPanel.BorderWidth = 2;
        serverPath = Request.PhysicalApplicationPath;
        string chosenMap = dropdownlistMap.SelectedItem.Text;

        Bitmap bm = new Bitmap(serverPath + chosenMap);
        int imageWidth = bm.Width;
        int imageHeight = bm.Height;
        bm.Dispose();

        FileInfo fi = new FileInfo(chosenMap);
        string imageSrc = "~/" + fi.Name;

        imgPanel.BackImageUrl = imageSrc;
        imgPanel.Width = imageWidth + 4;
        imgPanel.Height = imageHeight + 4;
        imgPanel.BorderColor = Color.Yellow;
        imgPanel.BorderStyle = BorderStyle.Groove;
        imgPanel.BorderWidth = 2;
酒解孤独 2024-10-25 04:17:47

说真的——这并不一定那么难。我刚刚为我正在设计的东西实现了这个......我意识到这个线程可能已经死了,但是嘿 - 我想出了一个更好的解决方案。

ASPX VB:

 ClientScript.RegisterStartupScript(Me.[GetType](), "Background",
"document.body.style.backgroundImage = " & Chr(34) &
"url('128-700.jpg')" & Chr(34) & ";", True)

就是这样...我直接从 VB 代码部分调用它。我仍在学习,但我知道在四处寻找并尝试不同的事情之后——这是尽可能简单的。

诀窍是——这段代码利用 Java 调用来更改背景而不是修改 CSS。

Seriously -- this doesn't have to be this hard. I just implemented this for something I am designing... I realize this thread is probably dead but hey -- I came up with a better solution IMO.

ASPX VB:

 ClientScript.RegisterStartupScript(Me.[GetType](), "Background",
"document.body.style.backgroundImage = " & Chr(34) &
"url('128-700.jpg')" & Chr(34) & ";", True)

That's it... I call it straight from the VB code part. I'm still learning but I know that after searching around and trying different things -- this was as straight forward as possible.

The trick is -- this code utilizes a call for Java to change the background versus modifying the CSS.

清风疏影 2024-10-25 04:17:47

点是url括号内的单双逗号;

navImageChange.Attributes.Add("style", "background-image:url('" + "your url" + "')");

Point is single-double comma in url brackets;

navImageChange.Attributes.Add("style", "background-image:url('" + "your url" + "')");

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文