简体   繁体   中英

ASP.Net Repeater Eval in an If statement

So I've been looking around for a good answer to this question, but haven't really found anything useful. Hopefully someone can shed some light on this for me.

Basically, I have a repeater that is backed by a database table. Inside the ItemTemplate for this repeater, I have some HTML elements that are populated with properties from each item in the list. Pretty standard stuff. However, there is a possibility that one of the items could be null. In that case, it would make sense for me to put some sort of if (blah != null) logic around the offending code. The only problem is, when I've tried to do so, ASP throws up on me, telling me that I can't use an if statement inside of <%# %> .

My question to the masses is this: if you can't use an if statement inside of <%# %> , then how are you supposed to do conditional logic based on the values of each item?

I know that you can call your own methods inside the repeater, but that won't work for what I'm trying to do.

Below is what I'm trying to accomplish, to better illustrate my point.

<asp:Repeater runat="server" ID="repeater">
    <ItemTemplate>
        <div class="item-wrap">
            <% if(Eval("imageUrl") != null) { %>
            <div class="plan-img">
                <asp:Image runat="server" ImageUrl='<%# Eval("imageUrl") %>'/>
            </div>
            <% } %>
        </div>
    </ItemTemplate>
</asp:Repeater>

inside your ItemTemplate write the markup like this:

<asp:Panel runat="server" Visible='<%# Eval("imageUrl") != null %>'>
    <asp:Image runat="server" ImageUrl='<%# Eval("imageUrl") %>'/>
</asp:Panel>

Basically you can't mix code <% with databinding constructs <%# .

My advice would be to add the following property in your CodeBehind:

    protected YourClass DataItem
    {
        get
        {
            return (YourClass)this.Page.GetDataItem();
        }
    }

and then write the markup without Eval() :

    <asp:Image runat="server" ImageUrl='<%# DataItem.imageUrl %>'/>

You're supposed to generate the same content for every item in the template. If you don't need to use it for a particular item just set it's visibility to false in the binding events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM