【问题标题】:Dynamically add HTML to ASP.NET page将 HTML 动态添加到 ASP.NET 页面
【发布时间】:2011-07-27 09:23:24
【问题描述】:

有人能告诉我将 HTML 内容动态添加到 ASP.NET 页面的“正确”方法是什么吗?

我知道以下声明方法。

//Declaration
<%= MyMethodCall() %>


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

有没有更好或最佳实践的方法?

编辑:我正在根据特定文件夹中的图像动态构建 Galleriffic 照片库。

【问题讨论】:

    标签: c# asp.net html declarative


    【解决方案1】:

    取决于你想做什么。

    对于控件/文本,我通常使用 LiteralControl 并将 Text 属性设置为我要添加的 HTML,然后可以将此控件添加到页面上您希望它出现的任何位置

    LiteralControl 参考是 here

    好吧,看看你想要的 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);
    

    【讨论】:

    • 与我指定的方法相比,这种方法有哪些优势? PS:感谢您提供全面的示例!
    • 这段代码很糟糕。为什么不使用中继器?或 .aspx 中的 for。连接字符串以创建 HTML 不是我认为的最佳实践
    • 在 C# 代码中组装标记应该是绝对的最后手段,因为它会造成让 Cthulhu 感到自豪的维护噩梦。至少,封装到用户或服务器控件中。
    • 是的,就字符串/HTML concat 而言,您是对的,我只是快速将该示例放在一起说明这一点
    【解决方案2】:

    有几种方法可以做到这一点,具体使用哪一种取决于您的场景和偏好。

    • Web 用户控件:可以动态添加,您可以获得 Visual Studio 的完整编辑器支持。
    • XML 文字(仅限 VB.NET):在代码中快速组合 HTML 的非常方便的方法。
    • 模板:将纯 HTML 文档添加到您的解决方案中,并将其作为资源包含在内。然后您将获得编辑器支持,并且您的代码不会与 HTML 源代码混淆。

    【讨论】:

      【解决方案3】:

      aspx:

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

      后面的代码:

      DIV1.InnerHtml = "some text";
      

      【讨论】:

      • 对于任何实质性的东西,比如“照片库”,我建议使用 react 之类的东西,但这个问题来自 2011 年,对于快速而肮脏的东西,这个答案是一个很好的解决方案
      【解决方案4】:

      另一种选择

      //.aspx
      <asp:Literal ID="myText" runat="server"></asp:Literal>
      
      
      //.aspx.cs
      protected Literal myText;
      myText.Text = "Hello, World!";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多