Reputation: 841
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>
Upvotes: 3
Views: 11788
Reputation: 21485
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 %>'/>
Upvotes: 8
Reputation: 35107
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.
Upvotes: 0