2016-08-02 57 views
0

我試圖從asp.net代碼隱藏中將幾個<img>標記添加到我的html文檔中。我看着Adding Html from Code Behind in Asp.net,它似乎是解決方案,但我不知道divcontrol.Controls.Add如何確定它將開始添加html。據我所知,它是在HTML的末尾。我還發現Write Html Markup from code behind in asp.net,但我不確定如何使用它。修改並從asp.net添加html

所以這裏是我使用的html。我怎麼可以添加img標籤我還包括?:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<title>Gallery</title> 
    <script type='text/javascript' src='/jquery-11.0.min.js'></script> 
    <script type='text/javascript' src='theme-tiles.js'></script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <h2>Tiles - Justified</h2> 
    <div id="gallery" style="display:none;"> 
    </div> 

    <script type="text/javascript"> 

     jQuery(document).ready(function() { 

      jQuery("#gallery").gallery({ 
       tiles_type: "justified" 
      }); 

     }); 

    </script> 
    </form> 
</body> 

</html> 

這是<img>標籤,我需要的<div id="gallery">標籤之間添加:

<img alt="img1" 
    src="images/thumbs/tile1.jpg" 
    data-image="images/big/tile1.jpg" 
    style="display:none"/> 
</a> 

這是我會用代碼添加html

HtmlGenericControl divcontrol = new HtmlGenericControl(); 
divcontrol.Attributes["class"] = "sxro sx1co"; 
divcontrol.TagName = "div"; 
pnlUserSearch.Controls.Add(divcontrol); 
Label question = new Label(); 
divcontrol.Controls.Add(question); // add to the new div, not to the panel 

回答

0

如果要創建客戶端HTML(而不是服務器控件),那麼你可以創建一個Literal,像這樣:

<div id="gallery" style="display:none;">  
    <asp:Literal runat="server" ID="MyLiteral" /> 
</div> 

然後,在你的代碼隱藏,設置

MyLiteral.Text = "<whatever html you want>" 

我回答你的問題從字面上(沒有雙關語意。)可能有更好的/其他的方式來完成最終目標。將「普通」客戶端HTML與webforms混合可能會變得雜亂無章。 Webforms希望您盡一切努力。

如果您的容器div(gallery)是服務器控件,它可能會更有意義。如果你想添加多個圖像,那麼你可能需要的是一個Repeater

說實話,如果你的開發路徑不是太遠,最好看看ASP.NET MVC。


另一種方法:

只需添加您的圖像本身直接在標記服務器控件。

<div id="gallery" style="display:none;">  
    <img runat="server" ID="MyImage" Visible="False"/> 
</div> 

在你的後臺代碼,如果你想顯示它,

MyImage.Src = "/image url"; 
MyImage.Visible = true;