Render image properties in EPiServer 7

Denna artikel har migrerats från en tidigare version av vår webbplats och kan därför avvika i utseende och funktionalitet.

Den här artikeln är inte översatt till svenska och visas därför på engelska istället.


In this post we'll look at how to use ASP.NET MVC display templates to control how image properties are rendered when using the PropertyFor helper method.

Uppskattad lästid : 4 minuter

Gå till avsnitt

Different rendering based on UIHint attribute

In EPiServer 6 we had multiple property types for URLs, such PropertyDocumentUrl and PropertyImageUrl. The property type would determine how the property is rendered: PropertyDocumentUrl would be rendered as a link (with a link selector rendered in edit mode) whereas PropertyImageUrl would be rendered as an image (with an image selector in edit mode).

Another example is that we no longer have PropertyString and PropertyLongString types. Instead we use the plain .NET type string and use UIHint attributes to specify if a string is “long” (i.e. one that should be edited in a textarea as opposed to a textbox in edit mode).

In EPiServer 7 the number of data types for page type properties are fewer and are in most cases “real” data types as opposed to specialized types used specifically for page type properties. For example, instead of PropertyDocumentUrl and PropertyImageUrl we simply declare page type properties of type Url. Which kind of URL it is, is determined by a UIHint attribute.

Defining an image URL property

My page type (or model) has a page type property called Portrait defined like this:

[ContentType]
public class Person : PageData
{
    [UIHint(UIHint.Image)]
    public virtual Url Portrait { get; set; }
}

Note that I’ve added a UIHint attribute to indicate that this particular Url property is for an image.

Rendering a URL property with an Image UIHint attribute

If we would simply use the PropertyFor helper method to render our Portrait property…

@Html.PropertyFor(model => model.Portrait)

…the URL would simply be rendered as a link, not as an image:

image

Add a display template for image properties

We can add an ASP.NET MVC display template for the Image UI hint by creating a new partial view called Image.cshtml (named after the UI hint) in the /Views/Shared folder:

image

This will result in this partial view being used to render properties decorated with the “Image” UI hint. We could put something like the following in the partial view to render the image (note that the model type is Url since that’s the original property type):

@model EPiServer.Url

<img src="@Model" alt="" />

Now we can use the PropertyFor helper method just as before to have image properties render an actual <img> tag while getting benefits such as the view not being rendered if there’s no property value (i.e. no image selected) and OPE (on-page edit) support:

image