Display Image from Media Library in Umbraco 7

Informagic picture Informagic · Apr 17, 2014 · Viewed 36.2k times · Source

This should be something embarrassingly simple, but I can't get it to work: I'd simply like to display an image that was uploaded to the Umbraco Media Library (Umbraco 7.1.1) within a Partial View template. The code is

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{   
    var imgNode = CurrentPage.BannerBackgroundImage;
    var imgUrl = umbraco.library.NiceUrl(imgNode);
    <div id="banner-wrapper" style="background: url('@imgUrl') center center no-repeat;">
        <!-- some irrelevant content -->
    </div>
}

where BannerBackgroundImage is a custom property of the page. When this is displayed, however, the @imgUrl gets replaced with #.

Other alternatives that I've tried are multiple Media Picker images, how to display a Media Picker image, get image from media with Razor, and display image from Media Picker, to name but a few.

I'd really appreciate if somebody could help me with what I believe is a rookie question!

Answer

Jesus Mogollon picture Jesus Mogollon · Jun 5, 2014

I found this way easy and clean:

@if (CurrentPage.Image != null && !(CurrentPage.Image is Umbraco.Core.Dynamics.DynamicNull))
{
    var m = Umbraco.Media(CurrentPage.Image);

    <img src="@m.Url" alt="@m.UrlName" />
}

I hope that it helps somebody else