Search code examples
asp.netvb.netmaster-pagescode-behind

What is the best practice for ouputting data from a collection on an ASP.net Page?


I've ported a page from classic ASP to ASP.net. Part of what happens in this page is that a collection of custom types is generated and then displayed via Response.Write() commands. I'd like to get the business logic separated out into a code behind file (and maybe move this all into a user control), but I can't seem to figure out how I'd actually display the collection once it's been generated. I want to specify a master page here, too, so the code can't stay inline. Here's a very stripped down version of the current code:

<%
Dim objs as ArrayList = New ArrayList()

For i = 0 To 2
    Dim obj as Obj = New Obj()

obj.setProp1("ASDF")
obj.setProp2("FDSA")

objs.Add(obj)
Next i
%>

<table>
<thead>
    <tr>
        <th scope="col">Property 1</th>
        <th scope="col">Property 2</th>
    </tr>
</thead>
<tbody>
<%
For Each obj As Obj In objs
Dim objProp1 As String = obj.getProp1
Dim objProp2 As String = obj.getProp2
%>                  
    <tr>
        <td><% Response.Write(objProp1)%></td>
        <td><% Response.Write(objProp2)%></td>
    </tr>
<%
Next
%>
</tbody>
</table>

What is the ".net" way of doing this?


Solution

  • You can also take a look at the ListView control which is a newer version of the repeater that Joe R mentioned. There's a great tutorial on what you can do with a ListView on ScottGu's blog.

    Your code would basically turn into something along these lines:

    <asp:ListView id="ListView1" runat="server" enableviewstate="false">
        <LayouTemplate>
            <table>
                <thead>
                    <tr>
                        <th scope="col">Property 1</th>
                        <th scope="col">Property 2</th>
                     </tr>
                 </thead>
                 <tbody>
                     <asp:Placeholder runat="server" id="ItemPlaceholder" />
                 </tbody>
            </table>
        </LayouTemplate>
        <ItemTemplate>
            <tr>
                <td><%# Eval("objProp1" )%></td>
                <td><%# Eval("objProp2" )%></td>
            </tr>
        </ItemTemplate>
    </asp:ListView>
    

    These guys consider using Eval to not be a good practice, but it made writing the example easier. If you're presenting read only data, don't forget to turn off ViewState or your pages will get very big very quickly.

    EDIT Also found a feature comparison chart between the different list style controls here.