Umbraco how to use image property id to get URL

22,298

Solution 1

Solutioin if anyone happens to stumbles upon this:

 var bannerId = Umbraco.Media(banner.image); //banner.image is the property id.
 var bannerUrl = bannerId.Url;

Solution 2

To do the same within an MVC controller / API Contoller once you have the "media ID" you can also use the UmbracoHelper.

var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
var image = umbracoHelper.Media(mediaID);      // mediaID =  the (int)ID of the media
var imageURL = image.url;                      // imageURL now has the site root relative path of the media item

Solution 3

It's much better to use strongly typed models in Umbraco nowadays:

var bannerMediaItem = Umbraco.TypedMedia(banner.image); //banner.image is the property id.
var bannerUrl = bannerMediaItem.Url;
Share:
22,298
rtn
Author by

rtn

Front end web developer

Updated on May 23, 2020

Comments

  • rtn
    rtn almost 4 years

    Ok am am very new to Umbraco/C# and what I am trying to do is loop through a custom media type to build banners for the home page of my application and the @bannerUrl always returns the images property id and not the file path to the resource. How would you go about retrieving the image file path from a custom media type created in Umbraco.

    See code for example:

    var mediaFolder = Umbraco.Media(mediaFolderId);
    var banners = mediaFolder.Children();
    
    foreach (var banner in banners)
        {
         var bannerUrl = banner.image;
    
          <div style="background-image:url(@bannerUrl);"></div>
    
     }
    

    The variable bannerUrl always returns the image id by default and not the file path for the URL. How can I get the file path working? When inspecting the contents of the banner object in the debugger in VS I notice of the Url property has the following error:

    Url = 'banner.Url' threw an exception of type 'System.NotSupportedException'
    

    You would of though I could use something along the .Url lines but that dose not seem to work, so any suggestions how I would go about getting the URL the image property in Umbraco using the Dynamic way.

    Thanks.

  • Ḟḹáḿíṅḡ Ⱬỏḿƀíé
    Ḟḹáḿíṅḡ Ⱬỏḿƀíé over 8 years
    Stumbled upon and used. Many thanks for straightforward solution.
  • Base33
    Base33 over 7 years
    You don't want to use this. This accesses the database and does slow down page loading time. Use the UmbracoHelper, specified below.