Render image properties with the PropertyFor helper

Ted
Ted
Vote:
 

I have a page type property called "Portrait" which is of type Url with an image UI hint:

[UIHint(UIHint.Image)]
public virtual Url Portrait { get; set; }

 

If I render this property with the PropertyFor helper method, the URL will be rendered as a link - not as an image.

 

I want the property to be rendered as an image (an <img> tag) which can be clicked in OPE mode to select an image. Also, unless in OPE mode, I don't want anything rendered if the property hasn't been set.

I could do something like this to get OPE support for the <img> tag:

<img src="@Model.CurrentPage.Portrait" @Html.EditAttributes(x => x.CurrentPage.Portrait) />

However, I'd also need to hide this if the property hasn't been set - unless in OPE mode... :/ In other words, quite a bit of code for something trivial.

Surely there's some clever way of rendering Url properties differently depending on which kind of URL it is?

What am I missing? :)

#65821
Feb 11, 2013 15:10
Ted
Vote:
 

In the meantime, this is the (rather bloated) code from my view:

@if (Model.Portrait != null || PageEditing.PageIsInEditMode) 
{
    <img src="@Model.Portrait" alt="@Model.PageName" @Html.EditAttributes(p => p.Portrait) />
}

    

#65825
Edited, Feb 11, 2013 16:09
Vote:
 

Hi

The reason for this is that EPiServer doesn't come with a specific display template for image urls, so it will use the Url.ascx for any kind of url property.

The best way to work around this issue is to add a display template named the same as the ui hint with the code for that specific property. In this case dropping an Image.ascx/cshtml into /Views/Shared/DisplayTemplates containing something like the code below should do the trick

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<EPiServer.Url>" %>
<%@ Import Namespace="EPiServer.Web.Mvc.Html" %>

<img src="@Url.PageUrl(Model.ToString())" />

Such a template will be included in future versions of EPiServer.

Regards

Per Gunsarfs

#65827
Feb 11, 2013 16:15
Ted
Vote:
 

Ah, didn't realize there was a convention for UIHint-specific display templates! Thanks a lot, appreciate your help!

#65828
Feb 11, 2013 16:18
Vote:
 

Yeah, that's the way you can differentiate rendering between properties whose value are of the same type. And since UIHint is a .NET thingy, and nothing we've invented, we can simply lean on built in functions in this case :)

Hopefully it should work pretty much straight forward. Let us know if you run into any issues.

#65829
Feb 11, 2013 16:24
Ted
Vote:
 

Yeah, I should have realized that - I confused myself by looking for something EPiServer-specific so it didn't even strike me that MVC already has that mechanism in place! :/

Thanks again!

#65830
Feb 11, 2013 16:40
Ted
Vote:
 
#65851
Edited, Feb 12, 2013 11:56
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.