前台代码:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_OnItemDataBound">
<ItemTemplate>
<p>
<a href='test.aspx?Category=<%# Eval("Id") %>'><%# Eval("Id") %></a>
</p>
<asp:Repeater ID="Repeater2" runat="server">
<ItemTemplate>
<li><a href='<%# Eval("href") %>'>
<%# Eval("text")%></a></li>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
<ItemTemplate>
<p>
<a href='test.aspx?Category=<%# Eval("Id") %>'><%# Eval("Id") %></a>
</p>
<asp:Repeater ID="Repeater2" runat="server">
<ItemTemplate>
<li><a href='<%# Eval("href") %>'>
<%# Eval("text")%></a></li>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
使用的类结构是这样的,Category类包含了一个Link类的集合
public class Cateogory
{
public int Id { get; set; }
public List<Link> Links { get; set; }
}
public class Link
{
public string href { get; set; }
public string text { get; set; }
}
{
public int Id { get; set; }
public List<Link> Links { get; set; }
}
public class Link
{
public string href { get; set; }
public string text { get; set; }
}
为了演示,不从数据库读取,自己填充一些数据
private static List<Cateogory> GetData()
{
List<Cateogory> categories = new List<Cateogory>();
for (int i = 0; i < 5; i++)
{
Cateogory c = new Cateogory();
c.Id = i;
List<Link> lst = new List<Link>();
for (int j = 0; j < 3; j++)
{
Link l = new Link();
l.href = "test.aspx?Category=" + i + "&Id=" + j;
l.text = "Cateogory:" + i + ";Id:" + j;
lst.Add(l);
}
c.Links = lst;
categories.Add(c);
}
return categories;
}
{
List<Cateogory> categories = new List<Cateogory>();
for (int i = 0; i < 5; i++)
{
Cateogory c = new Cateogory();
c.Id = i;
List<Link> lst = new List<Link>();
for (int j = 0; j < 3; j++)
{
Link l = new Link();
l.href = "test.aspx?Category=" + i + "&Id=" + j;
l.text = "Cateogory:" + i + ";Id:" + j;
lst.Add(l);
}
c.Links = lst;
categories.Add(c);
}
return categories;
}
Page_Load的时候绑定Repeater1
protected void Page_Load(object sender, EventArgs e)
{
List<Cateogory> categories = GetData();
Repeater1.DataSource = categories;
Repeater1.DataBind();
}
{
List<Cateogory> categories = GetData();
Repeater1.DataSource = categories;
Repeater1.DataBind();
}
关键在这里了,Repeater1绑定的时候,方法里要获取子类的集合,如果是数据库,应该是获取Id,再从数据库中根据Id取数据列表.
protected void Repeater1_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater rpt = e.Item.FindControl("Repeater2") as Repeater;
if (rpt != null)
{
Cateogory category = e.Item.DataItem as Cateogory;
rpt.DataSource = category.Links;
rpt.DataBind();
}
}
}
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater rpt = e.Item.FindControl("Repeater2") as Repeater;
if (rpt != null)
{
Cateogory category = e.Item.DataItem as Cateogory;
rpt.DataSource = category.Links;
rpt.DataBind();
}
}
}
最后的效果如图: