Wednesday, June 5, 2013

ASP.NET strongly typed repeater

Today, I looked at old ASP.NET code, and saw something like this:
<asp:Repeater runat="server" ID="repTourDepartureCache" >
    <ItemTemplate>
        <tr>
            <td>
                <%# Eval("Key") %>
            </td>
        </tr>
    </ItemTemplate>
</asp:Repeater>

The problem is that the binding done here is done by so called "magic string". And if someone will change a property name from "Key" to something else this code will stop working. Programmer writing this code was not aware that in .NET 4.5 strongly typed data binding was introduced by using additional attribute ItemType. The above code should look:
<asp:Repeater runat="server" ID="repTourDepartureCache" ItemType="TTC.TT.Entities.ViewModels.PrettyPrintedTourDeparture">
    <ItemTemplate>
        <tr>
            <td>
                <%# Item.Key %>
            </td>
        </tr>
    </ItemTemplate>
</asp:Repeater>

There is a full Intellisense support for this kind of binding. And it makes refactoring easier. For generic types ItemType definition looks like:
<asp:Repeater runat="server" ID="repTourDepartureCache" ItemType="System.Collections.Generic.KeyValuePair`2[System.String, System.String]">
</asp:Repeater>

No comments: