I am just a beginner in ASP.NET. My question is simple, I wanna add list items dynamically from the code behind file and I want each item to have a text and couple of images as hyperlinks. The HTML sample should be like,
<ul> <li>do foo <a href="#" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"><img src="some_image.png" /></a></li> <li>do bar <a href="#" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"><img src="some_image.png" /></a></li> ... </ul>
The number of items is dependent on the collection retrieved by the code behind file.
P.S. my code behind file is written in C#
Answers:
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
The Repeater control is the simplest way to create a customized bulleted list, plus it gives you complete control over the HTML you generate. To use it, set up a template like this:
<ul>
<asp:Repeater runat="server" ID="ListRepeater">
<ItemTemplate>
<li>do foo <a href='#'><img src='<%# Eval("ImageSource") %>' /></a></li>
</ItemTemplate>
</asp:Repeater>
</ul>
Then in your code-behind (or declaratively in your markup, depending on your preference), set the repeater’s data source and bind it:
void Page_Load(object sender, EventArgs e) {
// Some method you've defined to get your images
List<string> imageList = GetImages();
ListRepeater.DataSource = imageList;
ListRepeater.DataBind();
}
ASP.NET renders the template once for each item in your data source.
The Repeater control has more features than what I’ve shown here, but this should get you started. Good luck!
Edit: a year after writing this answer, I still think repeaters are the best option among server controls, but more and more I prefer foreach statements right in my .aspx templates:
<ul>
<% foreach(Image image in this.Images) { %>
<li>do foo <a href='#'><img src='<%= image.Source %>' /></a></li>
<% } %>
</ul>
Method 2
Just use the Repeater control. Simply and easy. 🙂
Method 3
ASP.Net BulletedList. MSDN
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