以下示例使用 ListView 而不是 Repeater。 ListView 很棒,因为它们比 Repeater 具有更大的灵活性。此外,正如您在下面的示例代码中看到的,绑定嵌套/子 ListView 都可以通过声明方式完成没有任何隐藏代码.
以下代码将产生的示例
ASPX
<asp:ListView runat="server" ID="lvw">
<LayoutTemplate>
<ul>
<li id="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<asp:LinkButton runat="server" CommandArgument='<%# Eval("Name")%>'><%# Eval("Name")%></asp:LinkButton>
<asp:ListView runat="server" ID="lvw2" DataSource='<%# Eval("Children")%>'>
<LayoutTemplate>
<ul>
<li id="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li><asp:LinkButton runat="server" CommandArgument='<%# Eval("Name")%>'><%# Eval("Name")%></asp:LinkButton></li>
</ItemTemplate>
</asp:ListView>
</li>
</ItemTemplate>
</asp:ListView>
C#
lvw.DataSource = personList;
lvw.DataBind();
正如您所看到的,在 C# 代码中,我创建了一个“Person”列表,如下所示。每个 Person 对象都有一个子 Person 对象的列表。通过以这种方式创建对象,绑定 ListView 实际上就像我所展示的一样简单。使用下面的 Person 对象运行一个快速示例,以便您亲自查看。
人物对象
public class Person
{
public string name { get; set; }
public List<Person> Children { get; set; }
}
对于您的测试,您可以创建一个 Page_Load 方法,如下所示:
protected void Page_Load(object sender, EventArgs e)
{
List<Person> personList = new List<Person>();
Person person1 = new Person() { name = "Child 1" };
Person person2 = new Person() { name = "Child 2" };
List<Person> childPersonList1 = new List<Person>();
childPersonList1.Add(person1);
childPersonList1.Add(person2);
Person person3 = new Person() { name = "Person 1" };
person3.Children = childPersonList1;
personList.Add(person3);
Person person4 = new Person() { name = "Child 3" };
Person person5 = new Person() { name = "Child 4" };
List<Person> childPersonList2 = new List<Person>();
childPersonList2.Add(person4);
childPersonList2.Add(person5);
Person person6 = new Person() { name = "Person 2" };
person6.Children = childPersonList2;
personList.Add(person6);
Person person7 = new Person() { name = "Child 5" };
Person person8 = new Person() { name = "Child 6" };
List<Person> childPersonList3 = new List<Person>();
childPersonList3.Add(person7);
childPersonList3.Add(person8);
Person person9 = new Person() { name = "Person 3" };
person9.Children = childPersonList3;
personList.Add(person9);
lvw.DataSource = personList;
lvw.DataBind();
}
请参阅以下 StackOverflow 问题,了解有关 Repeater 和 ListView 之间差异的更多信息:Repeater、ListView、DataList、DataGrid、GridView...选择哪一个?