0
votes

I am trying to add a conditional statement to my repeater, but I am receiving the following error:

  • Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

The code I am trying to use is as follows:

<asp:Repeater ID="repLeftmenu" DataSourceID="xmlMenu" runat="server" EnableViewState="false">
  <HeaderTemplate>
    <ul class="leftMenu">
  </HeaderTemplate>
  <ItemTemplate>
    <li>
      <%  If XPath("@url").ToString = HttpContext.Current.Request.Url.AbsolutePath.ToString Then%>
        <a href="<%# XPath("@url") %>">
          <%# XPath("@title")%>
        </a>  
      <% Else %>
        <a href="<%# XPath("@url") %>">
          <%# XPath("@title")%>
        </a>              
      <%  End If%>
   </li>
 </ItemTemplate>
 <FooterTemplate>
   </ul>
 </FooterTemplate>
</asp:Repeater>    

Is there something wrong with my syntax?

Thanks, crjunk

1
Looking at your code, I see an if/else construct, but I see no difference between the code contained in the If Then ... Else and the code in the Else ... End If. Are you sure you need the if/else construct? - Michiel van Oosterhout

1 Answers

1
votes

You are using databinding expresions in regular code blocks, which is not supported. Databinding expressions should appear inside <%# ... %> blocks. Regular code blocks look like this: <% ... %>. (The only difference is the # at the beginning of the block.)

If you need a conditional inside a databinding block, you need to use an expression (simply said: a one-liner). The only way to accomplish this is by using the following code:

<%# If(XPath("Url").ToString = HttpContext.Current.Request.Url.AbsolutePath.ToString, "Display this when true", "Display this when false") %>

This can quickly become unwieldy when whole blocks of HTML are conditionally displayed. What you could do then is to create both blocks and set the visibility of each based on the conditional expression:

<span runat="server" visible='<%# XPath("Url").ToString = <%# If(XPath("Url").ToString = HttpContext.Current.Request.Url.AbsolutePath.ToString %>'>

  HTML that should be displayed when condition is true

</span>
<span runat="server" visible='<%# XPath("Url").ToString <> <%# If(XPath("Url").ToString = HttpContext.Current.Request.Url.AbsolutePath.ToString %>'>

  HTML that should be displayed when condition is false

</span>