Search code examples
c#sitefinitysitefinity-feathersitefinity-mvc

What object type is used for a single related image property in Sitefinity?


I've added a custom field to the news widget called RelatedImage which I want to display in a custom News List MVC template.

Note: the custom field is a Related media (images, videos, files) field with the limitation of "Multiple images can be uploaded or selected" set.

I can retrieve the image's URL by looping through custom field as follows:

@foreach (var relatedItem in item.Fields.RelatedImage)
{
    <li>@relatedItem.Fields.MediaUrl</li>
}  

The above code works and renders the URL.

Code like this outputs the correct value:

@item.Fields.RelatedImage.Length

However, when you set the limitation to "Only 1 image can be uploaded or selected" the model used for @item.Fields.RelatedImage changes so the above code throws exceptions because those properties don't exist.

What I need though is to render out only one image per news item in the list, but when I switch to the "Only 1 image..." limitation mode, I can't figure out what the model looks like or how to get a hold of its properties. So the following code won't work:

@item.RelatedItem("RelatedImage").Fields.MediaUrl

So the question for me right now is a frustrating one: How do I know what model is passed to my template/view? I've tried outputting various GetType().ToString() options but all i repeatedly get is ItemViewModel which doesn't help!

Edit - The following code actually works:

<img src="@Html.Raw(item.Fields.RelatedImage.Fields.MediaUrl)" />

But this was frustratingly difficult to figure out. How does one figure out what Type RelatedImage is. The property Fields is of type dynamic which makes things more tricky.


Solution

  • If the RelatedImage field is set to allow 1 image, the value returned will be of type Telerik.Sitefinity.Libraries.Model.Image.

    If the field is set to allow multiple images, the value returned will be an array of the same type i.e. Telerik.Sitefinity.Libraries.Model.Image[]

    To answer your question, you could check the type of the RelatedImage property:

    @if (item.Fields.RelatedImage is Image)
    {
        <img src="item.Fields.RelatedImage.Fields.MediaUrl" />
    }
    else if (item.Fields.RelatedImage is Image[])
    {
        foreach (var relatedItem in item.Fields.RelatedImage)
        {
            <img src="relatedItem.Fields.MediaUrl" />
        } 
    }
    

    A better way might be to use the GetRelatedItems extension found in Telerik.Sitefinity.RelatedData.RelatedDataExtensions when building your view model e.g.

    viewModel.RelatedImages = newsItem.GetRelatedItems<Image>("RelatedImage")
    

    which would return a collection of Image objects, regardless of the number of images selected.