Reputation: 47199
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
<%= 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.
Upvotes: 16
Views: 91189
Reputation: 2955
Another option
//.aspx
<asp:Literal ID="myText" runat="server"></asp:Literal>
//.aspx.cs
protected Literal myText;
myText.Text = "Hello, World!";
Upvotes: 0
Reputation: 3748
Aspx :
<div id="DIV1" runat="server"></div>
Code behind :
DIV1.InnerHtml = "some text";
Upvotes: 12
Reputation: 1509
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 = @"<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);
Upvotes: 29
Reputation: 12427
There are several ways to do that, which to use really depends on your scenario and preference.
Upvotes: 6