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.

<%= 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.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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

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

 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'><div></li>";

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


Method 2

Aspx :

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

Code behind :
DIV1.InnerHtml = "some text";

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

Method 4

Another option

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

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

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x