簡體   English   中英

動態添加HTML到ASP.NET頁面

[英]Dynamically add HTML to ASP.NET page

有人可以建議動態地將HTML內容添加到ASP.NET頁面的“正確”方法是什么?

我知道以下聲明方法。

//Declaration
<%= MyMethodCall() %>


//And in the code behind.
protected String MyMethodCall()
{
    return "Test Value";
}

有更好或最好的練習方式嗎?

編輯:我正在根據位於特定文件夾中的圖像動態構建Galleriffic照片庫。

取決於你想做什么。

對於控件/文本,我通常使用LiteralControl並將Text屬性設置為我想要添加的HTML,然后可以將此控件添加到您希望它出現的頁面上的任何位置

LiteralControl參考在這里

好吧,因為你想要它為Galleriffic,我想它會偽似出現......

 LiteralControl imageGallery = new LiteralControl();
    string divStart = @"<div id='thumbs'><ul class='thumbs noscript'>";
    imageGallery.Text += divStart;
    foreach ([image in images])
    {
      string imageHTML = @"<li><a class='thumb' name='optionalCustomIdentifier' ref='path/to/slide' title='your image title'>
                           <img src='path/to/thumbnail' alt='your image title again for graceful degradation' /></a>
                           <div class='caption'>[caption]<div></li>";

      imageGallery.Text += imageHTML;
    }
    string divEnd = @"</ul></div>";
    imageGallery.Text += divEnd;

    this.[divOnPage].Controls.Add(imageGallery);

Aspx:

<div id="DIV1" runat="server"></div>

代碼背后:

DIV1.InnerHtml = "some text";

有幾種方法可以實現,實際使用取決於您的方案和偏好。

  • Web用戶控件:可以動態添加,並獲得Visual Studio的完整編輯器支持。
  • XML文字(僅限VB.NET):在代碼中快速組合HTML的非常方便的方法。
  • 模板:向解決方案添加純HTML文檔並將其作為資源包含在內。 然后,您將獲得編輯器支持,並且不會使用HTML源代碼混亂您的代碼。

另外一個選項

//.aspx
<asp:Literal ID="myText" runat="server"></asp:Literal>


//.aspx.cs
protected Literal myText;
myText.Text = "Hello, World!";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM