Try our conversational search powered by Generative AI!

Conditional rendering of an image


Hi all!

I have a page property of type PropertyImageUrl. To render it I tried to use <EPiServer:Property PropertyName="MyImageProperty" runat="server" />, but that rendered an a-tag and not an img-tag. So instead I used <img src="<%# Container.CurrentPage["MyImageProperty"] %>" /> (in the ItemTemplate of a PageList) to render the image.

My problem now is that when MyImageProperty is not set, I dont want to render an img-tag at all. Not with an empty src attribute and not with a fallback image.

What is the recommended way to accomplish this?



May 08, 2012 18:59

<% if (Container.CurrentPage.IsValue("MyImageProperty") { %>

<img src="<%# Container.CurrentPage["MyImageProperty"] %>" />

<% } %>

IsValue is just an extension method that you can pull from EPiCode.Extensions.

May 08, 2012 20:21

Unfortunately that doesn't work. Visual Studio doesn't understand what Container is in the if statement (but it does in the img tag).

Any idea why?

May 09, 2012 7:05

How about: <img src="<%# Container.CurrentPage["MyImageProperty"] %>" runat="server" visible="<%# Container.CurrentPage.IsValue("MyImageProperty")" />

May 09, 2012 11:40

I'm not sure what visible is supposed to do, but setting visible="false" still displays the image. I can use "display: none" in this way though:

<img src="<%# Container.CurrentPage["MyImageProperty"] %>" runat="server" style="display: <%# Container.CurrentPage.IsValue["MyImageProperty"] ? "none" : "block" %>;" />

The problem is that the img-tag is still rendered. I don't want that. Isn't there a simple way to only render the tag (in a repeater) if some condition is met? I cannot be the only guy with this problem.


May 10, 2012 10:53

Fredriks example should work, but you could always wrap it with a placeholder:

<asp:placeholder visible='<%# Container.CurrentPage["MyImageProperty"] != null %>' runat="server">
<img src... />


May 10, 2012 11:24

The PlaceHolder control is exactly what I'm looking for. I wasn't aware of its existance, so thanks a lot for enlightening me!


May 10, 2012 12:43
This thread is locked and should be used for reference only. Please use the Episerver CMS 7 and earlier versions forum to open new discussions.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.