Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strong typed Container in WebForms

Take following example of code: (ASP.NET WebForms)

<asp:Content ContentPlaceHolderID="Contents" runat="server">
    <div class="blogpost-list">
        <asp:Repeater ID="blogList" runat="server">
            <ItemTemplate>
                <h2 class="blogpost-title">
                    <%# (Container.DataItem as BlogPost).Title %>
                </h2>
                <p class="blogpost-meta">
                </p>
                <p class="blogpost-content">
                    <%# (Container.DataItem as BlogPost).ParsedContent %>
                </p>
            </ItemTemplate>
        </asp:Repeater>
    </div>
</asp:Content>

Now what I want to do, is to avoid the content casting of the DataItem, ie. this line:

<%# (Container.DataItem as BlogPost).Title %>

I'm feeling inspired of the ASP.NET MVC, and was wondering if I could create a strong typed, view, and define it like:

<%@ Page
    Language="C#" MasterPageFile="~/Blog.Master" 
    AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
    Inherits="MyBlog.Default<MyStrongViewType>"
%>

Or any other way to avoid typecasting, and in general, have a strong typed view for ASP.NET WebForms.

Any good ideas?

like image 306
Claus Jørgensen Avatar asked Jun 01 '09 23:06

Claus Jørgensen


2 Answers

.NET 4.5 has a nifty solution for this. You just set the datatype you want to use on the repeater itself.

   <asp:Repeater ID="blogList" runat="server" ItemType="BlogPost">
        <ItemTemplate>
            <h2 class="blogpost-title">
                <%# Item.Title %>
            </h2>
            <p class="blogpost-meta">
            </p>
            <p class="blogpost-content">
                <%# Item.ParsedContent %>
            </p>
        </ItemTemplate>
    </asp:Repeater>

See:

  • http://weblogs.asp.net/scottgu/archive/2011/09/02/strongly-typed-data-controls-asp-net-vnext-series.aspx
  • http://www.asp.net/web-forms/videos/aspnet-web-forms-vnext/aspnet-vnext-videos-strongly-typed-data-controls
like image 106
jeremysawesome Avatar answered Nov 02 '22 05:11

jeremysawesome


This might be a bit late, but this seems a nice solution:

http://dotnetminute.blogspot.com/2012/04/creating-strongly-typed-repeater.html

like image 29
Ropstah Avatar answered Nov 02 '22 05:11

Ropstah