【问题标题】:ListView in ASP.NET and DataKeyNamesASP.NET 中的 ListView 和 DataKeyNames
【发布时间】:2013-12-16 11:32:00
【问题描述】:

我有一个 ListView,它绑定了一个 'A' 的列表,看起来像这样:

Class A
    Property Id as Integer
    Property TestStringA as String
    Property B as B
End Class

Class B
    Property Id as Integer
    Property TestStringB as String
End Class

在 ListView 中,我可以引用“链接属性”值(正确的术语是什么?):

<asp:ListView runat="server" ID="lwTest" ItemType="A">
    <LayoutTemplate>
        <tr runat="server" id="itemPlaceHolder"></tr>
    </LayoutTemplate>
    <ItemTemplate>
        <tr>
             <td><%# Item.TestStringA %></td>
             <td><%# Item.B.TestStringB %></td> (this is what I mean)
        </tr>
    </ItemTemplate>
</asp:ListView>

这在使用 Eval 方法时也有效(如果无法使用 'ItemType'):

<%# Eval(B.TestStringB) %>

我想循环 ListView 的项目并使用容器中的值,而不将它们保存在隐藏字段中(这不是“DataKeyNames”的目的吗?)。问题是,我不能通过 DataKeyNames 中的链接属性/属性(在示例 B.Id 中)来引用另一个对象的属性。当我这样做时,我收到一条错误消息,告诉我没有名为“B.Id”的属性):

<asp:ListView runat="server" ID="lwTest" ItemType="A" DataKeyNames"Id, B.Id">
    <LayoutTemplate>
        <tr runat="server" id="itemPlaceHolder"></tr>
    </LayoutTemplate>
    <ItemTemplate>
        <tr>
             <td><%# Item.TestStringA %></td>
             <td><%# Item.B.TestStringB %></td> (this is what I mean)
        </tr>
    </ItemTemplate>
</asp:ListView>

有谁知道这是否可行?我知道我可以添加将值直接返回到绑定对象的只读属性(但如果可能的话,我想避免这种情况):

Class A
    Property Id as Integer
    Property TestStringA as String
    Property B as B
    ReadOnly Property BId as Integer
        Get
            Return B.Id
        End Get
    End Property
End Class

Class B
    Property Id as Integer
    Property TestStringB as String
End Class

提前谢谢你!

【问题讨论】:

    标签: asp.net vb.net listview data-binding datakey


    【解决方案1】:

    首先,您只能使用类的直接属性作为 DataKeyNames。使用 Eval 指令,您可以更深入(但我相信只有一层)。

    您可以做的是通过代码隐藏更改列表视图中显示的内容。

    为此,添加一个 ItemDataBound 事件。 正在创建的项目的数据可以在 e.Item.DataItem 中找到,端将是 A 类型(在使用之前进行转换)。

    您应该能够直接通过 e.Item 访问您的控件(不知道该使用哪个属性),一旦找到正确的单元格,您可以为其设置任何您想要的文本并且由于您拥有 A 本身的绑定实例,因此您可以不受限制地调用您想要的任何属性或子属性。

    ListView 中的每个条目都会调用此函数,因此它们应该只为您提供当前条目的数据。

    希望这可以帮助您解决问题。

    【讨论】:

    • 感谢您的回答。由于无法在 DataKeyNames 中执行我想要的操作,因此我通过添加从链接属性返回值的 ReadOnly 属性来解决它。顺便说一句 - 您可以通过 Eval(或我在上面的方法中使用的 ASP.NET 4.5 中包含的新绑定函数,它也为您提供 IntelliSense 服务)深入一层。最后,我知道 ItemDataBound - 但在这种特定情况下,我想要一个不使用它的解决方案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多