显示具有根本不同的html表示的项目列表

时间:2014-03-21 08:47:25

标签: c# asp.net webforms

假设我有一个要在html中显示的项目列表。例如,它可以是:

List<MyBusinessObject> item;

其中MyBusinessObject定义如下:

public class MyBusinessObject
{
    public string Value1{ get; set; };
    public string Value2{ get; set; };
    public string Value3{ get; set; };
    public CategoryEnum Category{ get; set; };
}

假设我想根据类别显示每个MyBusinessObject与一个根本不同的html(例如不同的标签和css类)。

你会如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我建议在ItemTemplate中添加RepeaterMultiView。转发器允许添加自定义ItemTemplate,MultiView提供了一种在不同视图之间切换的简便方法。在Repeater的ItemDataBound事件处理程序中,您可以设置MultiView的正确视图。

转发器的标记

<asp:Repeater ID="rpt" runat="server" OnItemDataBound="rpt_ItemDataBound">
    <ItemTemplate>
        <asp:MultiView ID="multiView" runat="server" ActiveViewIndex="0">
            <asp:View runat="server">
                <asp:Panel runat="server">
                    <h1>View 1 - 
                    <asp:Label runat="server" 
                        Text='<%# DataBinder.Eval(Container.DataItem, "Category") %>' />
                    </h1>
                    <asp:Label runat="server" 
                        Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' />
                </asp:Panel>
            </asp:View>
            <asp:View runat="server">
                <asp:Panel runat="server">
                    <h1>View 2 - 
                    <asp:Label runat="server" 
                        Text='<%# DataBinder.Eval(Container.DataItem, "Category") %>' />
                    </h1>
                    <asp:Label runat="server" 
                        Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' />
                </asp:Panel>
            </asp:View>
        </asp:MultiView>
    </ItemTemplate>
</asp:Repeater>

代码隐藏

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var items = new List<MyDataItem>();
        items.Add(new MyDataItem() { Name = "Item1", Category = "Cat1" });
        items.Add(new MyDataItem() { Name = "Item2", Category = "Cat2" });
        items.Add(new MyDataItem() { Name = "Item3", Category = "Cat1" });
        items.Add(new MyDataItem() { Name = "Item4", Category = "Cat2" });
        items.Add(new MyDataItem() { Name = "Item5", Category = "Cat1" });
        rpt.DataSource = items;
        rpt.DataBind();
    }
}

protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item 
        || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var multiView = e.Item.FindControl("multiView") as MultiView;
        if (multiView != null)
            multiView.ActiveViewIndex = 
                ((MyDataItem)e.Item.DataItem).Category == "Cat1" ? 0 : 1;
    }
}

public class MyDataItem
{
    public string Name { get; set; }
    public string Category { get; set; }
}