Search code examples
razormodel-view-controllerumbraco

Umbraco - How to display an image from a media picker in the src of an IMG tag?


How do I get the url of an image selected using a media picker in umbraco - I have found the umbraco documentation which highlights that the return value of the media picker is the ID of the item picked. But surely this would be what you use to add images to your template?

I want to do ...

<div class="title" style="background-image:url(@Umbraco.Field("mediaPicker"))">
   <h1>...@Umbraco.Field("pageTitle")</p>
</div>

Thanks


Solution

  • As per the Umbraco Documentation you have two options, my advice would be to go with the first because I do believe that support for dynamics will be gone in a future version.

    1. Typed

    @if (Model.Content.HasValue("caseStudyImages"))
    {
        var caseStudyImagesList = Model.Content.GetPropertyValue<string>("caseStudyImages").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse);
        var caseStudyImagesCollection = Umbraco.TypedMedia(caseStudyImagesList).Where(x => x != null);
    
        foreach (var caseStudyImage in caseStudyImagesCollection)
        {      
            <img src="@caseStudyImage.Url" style="width:300px;height:300px" />      
        }                                                               
    }
    

    2. dynamic

    @if (CurrentPage.HasValue("caseStudyImages"))
    {
        var caseStudyImagesList = CurrentPage.CaseStudyImages.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        var caseStudyImagesCollection = Umbraco.Media(caseStudyImagesList);
    
        foreach (var caseStudyImage in caseStudyImagesCollection)
        {
            <img src="@caseStudyImage.Url" style="width:300px;height:300px" />
        }
    }
    

    The id is what is used to get the media object back as a TypedMedia object, from there you have access to the image url.