简体   繁体   English

动态添加HTML到ASP.NET页面

[英]Dynamically add HTML to ASP.NET page

Could someone please advise what the "correct" method is for adding HTML content to an ASP.NET page dynamically? 有人可以建议动态地将HTML内容添加到ASP.NET页面的“正确”方法是什么?

I am aware of the following declarative method. 我知道以下声明方法。

//Declaration
<%= MyMethodCall() %>


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

Is there a better or best practice way? 有更好或最好的练习方式吗?

EDIT: I am building a Galleriffic photo gallery dynamically depending on the images located in a specific folder. 编辑:我正在根据位于特定文件夹中的图像动态构建Galleriffic照片库。

Depends what you want to do. 取决于你想做什么。

For controls/text I normally use a LiteralControl and set the Text property as the HTML I want to add, then this control can be added anywhere on the page that you want it to appear 对于控件/文本,我通常使用LiteralControl并将Text属性设置为我想要添加的HTML,然后可以将此控件添加到您希望它出现的页面上的任何位置

LiteralControl reference is here LiteralControl参考在这里

ok seeing as you want it for Galleriffic, I guess it would pseudo-appear as such... 好吧,因为你想要它为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 : Aspx:

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

Code behind : 代码背后:

DIV1.InnerHtml = "some text";

There are several ways to do that, which to use really depends on your scenario and preference. 有几种方法可以实现,实际使用取决于您的方案和偏好。

  • Web User Controls: Can be added dynamically and you get the full editor support of Visual Studio. Web用户控件:可以动态添加,并获得Visual Studio的完整编辑器支持。
  • XML literals (VB.NET only): Very convenient way to quickly put together HTML in code. XML文字(仅限VB.NET):在代码中快速组合HTML的非常方便的方法。
  • Templates: Add a plain HTML document to your solution and include it as a resource. 模板:向解决方案添加纯HTML文档并将其作为资源包含在内。 Then you'll get editor support and you won't clutter your code with HTML source. 然后,您将获得编辑器支持,并且不会使用HTML源代码混乱您的代码。

Another option 另外一个选项

//.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