NET 转发器绑定列表 < 字符串 >

我正在将一个 List<string>绑定到一个转发器控件。现在我想使用 Eval函数 在 ItemTemplate中显示内容,如

<%# Eval("NAME") %>.

但是我不确定我应该使用什么来代替 NAME。

91532 次浏览

Just use <%# Container.DataItem.ToString() %>

If you are worried about null values you may want to refactor to this (.NET 6+)

<asp:Repeater ID="repeater" runat="server">
<ItemTemplate>
<%# Container.DataItem?.ToString() ?? string.Empty%>
</ItemTemplate>
</asp:Repeater>

Note if you are using less than .NET 6 you cannot use the null-conditional operator Container.DataItem?.ToString()

This should work just fine:

<ItemTemplate>
<%=this.GetDataItem().ToString() %>
</ItemTemplate>
rptSample.DataSource = from c in lstSample select new { NAME = c };

in the repeater you put

<%# Eval("NAME") %>

you have to use the databind syntax here or it will not work.

<%# this.GetDataItem().ToString() %>

Set the ItemType to System.String

<asp:Repeater ItemType="System.String" runat="server">
<ItemTemplate>
<%# Item %>
</ItemTemplate>
</asp:Repeater>

A more complete example based on the LINQ provided by @RobertoBr:

In code behind:

List<string> notes = new List<string>();
notes.Add("Value1")
notes.Add("Value2")


repeaterControl1.DataSource = from c in notes select new {NAME = c};
repeaterControl1.DataBind();

On page:

   <asp:Repeater ID="repeaterControl1" runat="server" >
<ItemTemplate>
<li><%# Eval("NAME")  %></li>
</ItemTemplate>
</asp:Repeater>

Inside Item Template

     <ItemTemplate>
<asp:Label ID="lblName"  runat="server" Text='<%# Eval("YourEntityName").ToString() ==""? "NA" : Eval("YourEntityName").ToString()%>'></asp:Label>
<ItemTemplate>

or Simply Add inside Item Template

<%# Eval("YourEntityName").ToString() ==""? "NA" : Eval("YourEntityName").ToString()%>