Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

c# - Customized bulleted list items in ASP.NET

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 &nbsp;<a href="#"><img src="some_image.png" /></a></li>
  <li>do bar &nbsp;<a href="#"><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#

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 &nbsp;<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 &nbsp;<a href='#'><img src='<%= image.Source %>' /></a></li>
    <% } %>
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...