Strongly typed access to your page data objects inside ItemTemplate

Posted on May 10, 2012 by Frederik Vig in ASP.NET, EPiServer

Here’s a little quick tip on how I usually set up my code to get strongly typed access to my page types inside Repeaters, ListViews, PageLists etc.

I use PageTypeBuilder in all my projects so I’m going to use it in the examples here as well, but you could just use the regular PageData objects instead (with a little more code).

<asp:Repeater runat="server" ID="rptNews">
    <HeaderTemplate>
        <div class="entries">
    </HeaderTemplate>
    <ItemTemplate>
	<%# SetItem(Container.DataItem) %>
	    <div class="entry">
	    <a href="<%# NewsPage.LinkURL %>">
		<img src="<%# NewsPage.ListImage %>" runat="server" visible="<%# NewsPage.ListImage.IsNotNullOrEmpty() %>" />
		<h2><%# NewsPage.Heading %></h2>
	    </a>
	    <div class="date">
		<%# NewsItem.StartPublish.ToString("dd.MM.yyyy") %></div>
	    </div>
    </ItemTemplate>
    <FooterTemplate>
	</div>  
    </FooterTemplate>
</asp:Repeater>

The thing to note here is that I’m calling the method SetItem(), which sets the current news page for me.

protected string SetItem(object dataItem)
{
    this.NewsPage = dataItem as StandardPage;
 
    return string.Empty;
}

NewsPage is just a auto property of type StandardPage.

Update: 13.05.2012

Thanks to Jon’s comment, we can simplify this code even more. Instead of using the SetItem method we can use the GetDataItem() method from the Page class.

protected StandardPage NewsPage { get { return Page.GetDataItem() as StandardPage; }}

This gives me strongly typed access to my objects. In ASP.NET 4.5 this will be even simpler since strongly typed access (model binding) will be built into controls like the Repeater, take a look at Scott Guthrie’s post if you’re curious about ASP.NET 4.5.

Related Posts: