Question

Kind of related to my other question - I've only ever used HTMLControls with runat="server" and WebControls grudgingly, preferring to have control over the markup that gets generated (including the ids of the elements, etc.).

What's your suggestion for, say, iterating over the contents of a collection and generating a table or list without resorting to databinding or using Response.Write in a loop from the code-behind? I'm interested in the different approaches for creating clean, maintainable code.

Was it helpful?

Solution

When you say "databinding," are you speaking of binding a database result set to a Gridview or Repeater, etc. via a .Bind() call, or just using any ASP.NET server control (or HTML server control) in general?

Because, if you just want to avoid using server controls in general, but don't want to use Response.Write either, you're seriously limited in your options.

Personally, if you want control over markup, why not just loop through a SqlDataReader or something and then save the results to a Literal control, using HTML where applicable. Then within the page (wherever you want the data to appear) just do:

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

OTHER TIPS

There is nothing to stop you iterating over your collection directly in your aspx page.

 <ul>
     <% foreach(Person person in this.People) {%>

         <li><%=person.Firstname %> <%=person.Lastname %></li>

     <% } %>
 </ul>

In this example People is a list property on my codebehind. You will find many ASP.NET MVC projects are using this method.

@Brownie... yeah, but those are Response.Write statements... you're just using the shorthand format

Inspired by the first suggestion I've also tried adding a PlaceHolder to the aspx and then adding child controls to it programatically from the code-behind. I'm hoping I can create a user control for the repeating content and then add it to the PlaceHolder in a loop. This will allow the UI code to be nicely encapsulated and should hide all the StringBuilder action.

The repeater control is used for exactly what you want. It is a server control, but you specify what HTML is generated in the templates. You do databind, but isnt that just a shortcut for a manual loop?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top