Asp.net

身體上的動態背景圖像 (ASP.NET)

  • April 4, 2018

我有一種情況,文件夾中有大約 10-20 個不同的背景圖像。當我的網站載入時,我需要根據數據庫中的一些值選擇其中一個特定的圖像。

我考慮過在 body 標記上使用runat=server,然後在 page_load 上動態添加屬性,但是在我讀到的任何地方,人們都說這是一個非常糟糕的主意……另外,我試過了,但沒有工作(但是沒有調試太多)。

如何以“正確的方式”做到這一點?:-)

您可以通過通用 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 文件中引用它:

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

或作為body標籤的屬性

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

這些中的任何一個都應該能夠幫助您。

引用自:https://stackoverflow.com/questions/5066031