【问题标题】:Use of Container.DataItem in an ItemTemplate在 ItemTemplate 中使用 Container.DataItem
【发布时间】:2009-04-16 23:15:13
【问题描述】:

我无法让这个工作,我不知道为什么。

<ItemTemplate>
<% if (Field(((DataRowView)(Container.DataItem)), "Video File")  != "") {  %> 
<a href='upload/images/<%# Field(((DataRowView)(Container.DataItem)), "Video File")%>'>Download Link</a>
<% } else {  %>
<embed height="14" width="661" name="plugin" src="<%# ContentUploadURL%>/<%# Field(((DataRowView)(Container.DataItem)), "Audio File")%>" type="audio/mpeg" autostart="false" />
<% } %>
</ItemTemplate>

看起来很简单,但我只是得到这个错误:

编译器错误消息:CS0103: 名称“容器”中不存在 当前上下文

我整天都在做这个,我是一个在 asp 中工作的 CMS 的新手。我真的不想学习 ASP,只是为了让这件事发挥作用。

如果有人能指出我正确的方向,我将非常感激。

谢谢!

【问题讨论】:

  • 您的原始问题没有答案...使用属性Visible 是一种解决方法,但没有人使用if 语句回答这个非常重要的问题。

标签: c# asp.net data-binding


【解决方案1】:

您不能在数据绑定表达式之外使用 Container.DataItem 。

我建议你把你的代码改成这样(抱歉,我目前无法测试):

<ItemTemplate>
  <asp:HyperLink runat="server"
    Visible='<%# Eval("Video File") != "" %>'
    NavigateUrl='<%# Eval("Video File")' Text="Download Link" />

  <embed runat="server" Visible='<%# Eval("Video File") == "" %>'
    height="14" width="661" name="plugin"
    src="<%# ContentUploadURL%>/<%# Field(((DataRowView)(Container.DataItem)), "Audio File")%>"
    type="audio/mpeg" autostart="false" />
</ItemTemplate>

关键是根据数据项的“视频文件”字段设置两个控件的Visible属性。

另请参阅此问题:ASP.Net conditional databinding

【讨论】:

    【解决方案2】:

    哦,谢谢!那肯定有帮助。好的,所以我实际上需要更多的 html,所以我尝试了你指给我的占位符技术。

    所以,我现在有了这个:

    <asp:PlaceHolder id="PlaceHolder1" runat="server" Visible='<%# Eval("Video File") != "" %>'>
    Video Stuff
    </asp:PlaceHolder>
    
    <asp:PlaceHolder id="PlaceHolder2" runat="server" Visible='<%# Eval("Video File") == "" %>'>
    Audio Stuff
    </asp:PlaceHolder>
    

    它几乎可以工作,只是视频文件在两个实例上都可见,而它应该只在第一个实例上可见。

    我也试过这个:

    <asp:PlaceHolder id="PlaceHolder1" runat="server" Visible='<%# Eval("Video File") != "" %>'>
        Video Stuff
        </asp:PlaceHolder>
    
    <asp:PlaceHolder id="PlaceHolder2" runat="server" Visible='<%# Eval("Audio File") != "" %>'>
        Audio Stuff
        </asp:PlaceHolder>
    

    但这使得两者一直都在展示。我觉得它快到了。

    谢谢!

    【讨论】:

      【解决方案3】:

      哦,没关系,我明白了!

      终于成功了:

          <asp:PlaceHolder id="PlaceHolder1" runat="server" 
           Visible='<%# Field(((DataRowView)(Container.DataItem)), "Video File") != "" %>'>
          Video Stuff
          </asp:PlaceHolder>
      
          <asp:PlaceHolder id="PlaceHolder2" runat="server" 
           Visible='<%# Field(((DataRowView)(Container.DataItem)), "Video File") == "" %>'>
          Audio Stuff
          </asp:PlaceHolder>
      

      非常感谢如此

      【讨论】:

      • 很高兴你得到它。下次,编辑您的原始问题,而不是创建答案。这就是这里的做法。此外,仅供参考,您可以通过确保行不太长来避免丑陋的长代码块。用手把它们包起来。
      猜你喜欢
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      • 1970-01-01
      相关资源
      最近更新 更多