Introduction
The Repeater – User Control Pattern
asp.net

The Repeater – User Control Pattern

In my previous post in this series I showed you how a repeater is a very clean ASP.NET server control. It has a few problems though:

  • You cannot bind to a strongly-typed object.
  • If you want alternating items you have to write the markup twice.
  • You cannot reuse your layout or markup outside of the repeater

The first problem will be solved by .NET 4.5. The concept is illustrated on Scott Guthrie’s blog on  strongly typed data controls.

For the remaining two items there’s actually already a solution available in ASP.NET: a user control. We could abstract out our markup to a user control and then use that user control within our repeater. This will allows us to wrap alternating items with a different markup so that we only need to adapt what changes. Furthermore, we can create a strongly typed property on the user control so we can bind to it in a strongly typed way.

Because it’s a user control, it can also live outside of the repeater. Essentially what we’re doing here is creating a view over a business object. We can reuse this view wherever we want later on, and we could build different views of the same business object to be used according to the situation.

Partial Class personview Inherits System.Web.UI.UserControl Public Property Person As Person End Class

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="personview.ascx.vb" Inherits="personview" %> <span><%= Me.Person.LastName%></span> <span><%= Me.Person.FirstName%></span>

You can see from the code example that we are data binding directly to the instance of Person that we have assigned as a property. We can now use the user control like this in our repeater:

<asp:Repeater ID="repPeople" runat="server"> <ItemTemplate> <div class="row"> <view:person ID="per" runat="server" Person='<%# Context.DataItem %>' /> </div> </ItemTemplate> <AlternatingItemTemplate> <div class="altrow"> <view:person ID="altper" runat="server" Person='<%# Context.DataItem %>' /> </div> </AlternatingItemTemplate> </asp:Repeater>

We are now reusing the markup and we can apply the difference for the alternating items on the level of the repeater.

Usually I tend to create views for most of my business objects (or at least the ones I want to visualize). This way I can have several different views in separate user controls and I can reuse them within repeaters or even just as details. Within the user controls I tend to use just plain HTML, extended with some jQuery for client-side behavior.

On the client-side we can mimic a very similar behavior with jQuery. In my next post I will show you how you can plug in your jQuery-templates and still have one single view, for client-side and server-side.

Kenneth Truyers
View Comments
Next Post

jQuery Templates and ASP.NET User Controls

Previous Post

The coolest ASP.NET server control