I recently had the need to display a collections of items stored in profile in a Repeater control (let's say the collection was a shopping cart with purchase items), and after thinking about it, realized that there was no obvious way to hook up a collection stored in profile using the ObjectDataSource. I resorted to binding programmatically, which is of course always an option:
protected void Page_Load(object sender, EventArgs e)
{
itemsRepeater.DataSource = Profile.ShoppingCart.Items;
itemsRepeater.DataBind();
}
Once you get used to binding things declaratively, however, it just feels out of place to resort to programmatic binding. To do this declaratively, I decided to write a static helper class to bind to, a technique which I think others might find useful, hence this blog entry. I called the class ProfileBinder, and added it to the same source code file where I had defined my custom ShoppingCart and Item classes (placed in App_Code). I then used HttpContext.Current.Profile to retrieve the current profile, cast it to the ASP.NET-generated ProfileCommon class (this is a strongly-typed derivative from ProfileBase that is created from the profile settings in your web.config file) and I now had a class ready for consumption by an ObjectDataSource:
public static class ProfileBinder
{
public static List<Item> GetShoppingCartItems()
{
return ((ProfileCommon)HttpContext.Current.Profile).ShoppingCart.Items;
}
}
The final snippet is what my repeater and data source controls looked like with this new class:
<asp:Repeater runat="server" ID="_itemsRepeater" DataSourceID="_itemsDataSource">
<ItemTemplate>
<li><%# Eval("Description") %> - <%# Eval("Cost", "{0:c}") %></li>
</ItemTemplate>
</asp:Repeater>
<asp:ObjectDataSource runat="server" ID="_itemsDataSource"
SelectMethod="GetShoppingCartItems" TypeName="ProfileBinder" />
Posted
Oct 24 2005, 11:33 AM
by
fritz-onion