Wednesday, 16 February 2011

Tip of the day, strongly typed repeater dataitems

Do you recognize this type of code?
            <asp:repeater ID="MyRepater" runat="server">
                <ItemTemplate>
                    <span class="some-class"><%# DataBinder.Eval(Container.DataItem, "APropertyOnMyObject") %></span>
                </ItemTemplate>
            </asp:Repeater>

Wouldn't it be sweet if we could write something like this instead?
            <asp:repeater ID="MyRepater" runat="server">
                <ItemTemplate>
                    <span class="some-class"><%# Container.GetItem<MyObject>().APropertyOnMyObject %></span>
                </ItemTemplate>
            </asp:Repeater>
Then we have the object strongly typed and will get compile errors if we've messed up.. I don't know about you, but I find it nicer to read without all that boiler-plate-code too


Have you guessed what's coming next..? =]

Well now you can! Just throw this baby in a suitable place and import the namespace in your page (or via web.config to get it in all pages..)

    public static class RepeaterItemExtensions
    {
        public static T GetItem<T>(this RepeaterItem repeaterItem)
        {
            return (T)repeaterItem.DataItem;
        }
    }

No comments:

Post a Comment