简体   繁体   English

将ASP.NET Repeater控件与列表一起使用 <T> 对象数据

[英]Using the ASP.NET Repeater Control with List<T> object data

I have an ASP.NET web app that places several string data into an object as properties. 我有一个ASP.NET Web应用程序,该应用程序将几个字符串数据放入对象中作为属性。 The string data is sourced from a JSON feed from Twitter. 字符串数据来自Twitter的JSON提要。 A collection of my TwitterMessages is held in a Generic List. 我的TwitterMessages的集合保存在通用列表中。

What I want to do is use an asp:repeater to iterate through my List<T> to display all of the contents of the objects it holds, by using <%# Eval("MyURL") %> . 我想做的是通过使用<%# Eval("MyURL") %>来使用asp:repeater遍历List<T>以显示其持有的对象的所有内容。 MyURL is the name of a property inside my TwitterMessage object. MyURL是我的TwitterMessage对象中的属性的名称。

In a previous question I was advised to use the asp:Repeater template to display my data in a custom HTML table. 在上一个问题中,建议我使用asp:Repeater模板在自定义HTML表中显示我的数据。 So being able to use a template somehow or other, is really what I'm interested in. 因此,能够以某种方式使用模板是我真正感兴趣的。

Where I am struggling is in working out how to perform a databind to the Repeater so I can reference my object data in the .aspx page. 我正在努力的工作是研究如何执行与Repeater的数据绑定,以便可以在.aspx页中引用我的对象数据。

I am aware that I need to use the ItemDataBound method in order to make a data-bound event so that I can reference the property names in my string data object. 我知道我需要使用ItemDataBound方法来进行数据绑定事件,以便可以在字符串数据对象中引用属性名称。

Hope that's enough info for some much appreciated help! 希望这是足够的信息,以提供一些非常有价值的帮助! :) :)

It's pretty straightforward to databind to your repeater. 将数据绑定到中继器非常简单。 Depending on where your list object resides, you can either bind your repeater using markup, or codebehind. 根据列表对象所在的位置,您可以使用标记绑定转发器,也可以隐藏代码。

If you want to do it in markup, you should make an ObjectDataSource wrapper around the List. 如果要在标记中执行此操作,则应在List周围进行ObjectDataSource包装。 Something like this: 像这样:

<asp:Repeater ID="rpt" runat="server" DataSourceID="twitterFeedSource" >
<ItemTemplate>
<tr><td><%# Eval("MyURL") %></td></tr>
</ItemTemplate>
</asp:Repeater>

<asp:ObjectDataSource ID="twitterFeedSource" runat="server"
  SelectMethod="GetTheListOfTwitterFeedObjects"
  TypeName="myTwitterFeedClass"
>
</asp:ObjectDataSource>

The GetTheListOfTwitterFeedObjects method should return the list of objects. GetTheListOfTwitterFeedObjects方法应返回对象列表。 Each object would need to have the property MyURL . 每个对象都需要具有MyURL属性。 You can of course extend your template and bind to any other properties that your twitter objects have. 当然,您可以扩展模板并绑定到twitter对象具有的任何其他属性。

Otherwise, you can do it straight from the code. 否则,您可以直接从代码中进行操作。 Simply do something like this in Page_Load: 只需在Page_Load中执行以下操作即可:

if (!IsPostBack)
{
    myRepeater.DataSource = myGenericList;
    myRepeater.DataBind();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM