How to bind List to my repeater in asp.net?
public class Post
{
public int id { get; set; }
public string title { get; set; }
public string body { get; set; }
public List<Comments> comments { get; set; }
}
public class Comments{
public int id { get; set; }
public string author { get; set; }
public string text { get; set; }
}
My data layer returns 开发者_Python百科the data I need:
List<Posts> post = (List<Post>)myDataLayer.GetPostAsList();
post has just one post in it even though it is a List.
I have 2 repeater controls. The first is the posts repeater. The second is the comments repeater which is outside the Posts repeater.
How can I pull the List<Comments>
out of Posts and bind to the Comments repeater?
The simplest way:
<asp:Repeater runat="server" ID="rptPosts">
<ItemTemplate>
<!-- markup for posts here-->
</ItemTemplate>
</asp:Repeater>
<asp:Repeater runat="server" ID="rptComments">
<ItemTemplate>
<!-- markup for comments here-->
</ItemTemplate>
</asp:Repeater>
The thing left is to bind data:
protected override void DataBind()
{
var posts = myDataLayer.GetPostAsList();
// if there is at leat one post
if (posts.Any())
{
rptPosts.DataSource = posts;
rptPosts.DataBind();
// you mentioned that there should be only one post in the list
var comments = posts.First().comments;
rptComments.DataSource = comments;
rptComments.DataBind();
}
}
精彩评论