You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从嵌套Repeater中访问父Repeater的DataItem?

嵌套Repeater访问父级DataItem返回空白的解决办法

问题描述

我在ASP.NET中使用嵌套Repeater,尝试从子Repeater里访问父Repeater的DataItem,但始终返回空白,没有预期结果。

我的基础代码

<asp:Repeater ID="Products">
    <ItemTemplate>
        <%# Eval("product_name") %>
        <asp:Repeater ID="SubProducts">
            <ItemTemplate>
                <%# DataBinder.Eval(Container.Parent.Parent, "DataItem.product_name")%>
                <%# Eval("subproduct_name") %>
            </ItemTemplate>
        </asp:Repeater>
    </ItemTemplate>
</asp:Repeater>

已尝试的绑定写法

<%# DataBinder.Eval(Container, "NamingContainer.NamingContainer.DataItem.MyRepeaterDataItem")%>

<%# DataBinder.Eval(Container.Parent.Parent, "DataItem.prod_name")%>

我还试过把NamingContainer.NamingContainer替换成Parent.Parent,但都没有效果。

可行的解决方法

正确的绑定表达式

子Repeater里要访问父级的DataItem,得准确找到父Repeater的Item容器,正确的写法是:

<%# DataBinder.Eval(Container.NamingContainer.NamingContainer, "DataItem.product_name") %>

如果偏好强类型写法,可以替换成:

<%# ((YourProductEntity)((RepeaterItem)Container.NamingContainer.NamingContainer).DataItem).product_name %>

(注:将YourProductEntity替换为父Repeater数据源对应的实体类类型)

关键注意事项

  • 字段名匹配:确保父Repeater的DataItem中确实存在product_name字段,大小写完全一致
  • 容器层级:如果父Repeater的ItemTemplate里嵌套了额外容器控件(比如Panel、Div),需要增加NamingContainer的层级,例如Container.NamingContainer.NamingContainer.NamingContainer
  • 数据源验证:先确认父Repeater绑定的数据源中,目标字段有有效值,不是null或空字符串

内容的提问来源于stack exchange,提问作者brendo234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 19:22:55