Skip to content Skip to sidebar Skip to footer

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? I am aware of the following declarative method. //Declaration <%

Solution 1:

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 reference is here

ok seeing as you want it for Galleriffic, I guess it would pseudo-appear as such...

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

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

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

Solution 2:

Aspx :

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

Code behind :

DIV1.InnerHtml = "some text";

Solution 3:

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.
  • XML literals (VB.NET only): Very convenient way to quickly put together HTML in code.
  • Templates: Add a plain HTML document to your solution and include it as a resource. Then you'll get editor support and you won't clutter your code with HTML source.

Solution 4:

Another option

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


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

Post a Comment for "Dynamically Add Html To Asp.net Page"