开发者

ASP.NET Repeater Eval

开发者 https://www.devze.com 2023-01-18 11:45 出处:网络
I am trying to execute the following code in a .aspx page: <asp:Repeater ID=\"rptComentarios\" runat=\"server\">

I am trying to execute the following code in a .aspx page:

<asp:Repeater ID="rptComentarios" runat="server">
            <ItemTemplate>
              开发者_JS百科  <% if (Convert.ToInt32(Eval("int_tipo")) == 1)
                   { %>
                                        <div class="resp">
            <div class="top">
            </div>
            <div class="cont-resp">
                <h3>
                    <%# Eval("txt_nome") %></h3>
                <p>
                 <%# Eval("txt_comentario") %></p>
            </div>
        </div>
                   <% }
                   else
                   {%>
                               <div class="usuario">
            <div class="top">
            </div>
            <div class="cont-usuario">
                <h3>
                       <%# Eval("txt_nome") %></h3>
                <p>
                    <%# Eval("txt_comentario") %></p>
            </div>
        </div>
                   <% } %>
            </ItemTemplate>
            </asp:Repeater>

It throws a runtime exception in the first line:

  <% if (Convert.ToInt32(Eval("int_tipo")) == 1)

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

What's wrong? Any ideas?


I had a similar problem and the following code worked for me:

<asp:Repeater ID="rptComentarios" runat="server">
  <ItemTemplate>

    <asp:PlaceHolder ID="placeholderBlaBlaBla" runat="server" Visible='<%# Convert.ToInt32(Eval("int_tipo")) == 1 %>'>
      Your optional HTML
    </asp:placeholder>

    Other HTML

  </ItemTemplate>
</asp:Repeater>

Some more comments:

Please note that single quotes are used to define the value Visible attribute of asp:placeholder. I tried double quotes too and they didn't work.

Anytime you want to get some optionally displayed HTML you should use a control to show/hide it. asp:placeholder works fine for that purpose. Don't ever do <% if(..) { %> - this is evil.

<%# ... %> is used to calculate or display expressions inside a repeater. These expressions can be displayed as HTML or passed as attributes of server side controls. You can't use if inside it.


I think there needs to be a # sign for the enclosure <%# ..Eval...%>

Or try the full Eval version

<%# if (Convert.ToInt32(DataBinder.Eval(Container.DataItem, "int_tipo"))
                                                                    == 1) { %>
0

精彩评论

暂无评论...
验证码 换一张
取 消