Blog about tips & tricks for CMS enhancement


Get Media Url in code behind in Umbraco 8

The documentation of Umbraco 8 is under refinement since the eight installment of the CMS version has been launched.

When fiddling about with the new APIs of retrieving content I kind of got stuck upon retrieving a Media Picker's values - especially the media url of that property type.

The Media Picker documentation currently didn't give a clear approach upon how to retrieve the url value of once desired property outside the UmbracoViewPage template. In my case, I was trying to retrieve the property value of a Site Settings Page (for storing various multi-site content) media picker. More specific a custom Service instead of retrieving in the View of the Umbraco page.

Since I was out of scope for using the UmbracoViewPage, I found out that I needed to first of all set the Models Builder to generate the content statically to begin with. So I changed the following in the web.config:

    <add key="Umbraco.ModelsBuilder.Enable" value="true"/>
    <add key="Umbraco.ModelsBuilder.ModelsMode" value="AppData"/>

This will make it possible to cast content types in Umbraco with the default implemented of Files (Files.generated.cs), Folders (Folder.generated.cs), Images (Image.generated.cs) and Members (Member.generated.cs).

So with that in mind we may approach our content retrieval of the media url by the following snippet:

public string GetSiteLogotype()
    var logotypeAlias = SettingsPage.GetModelPropertyType(p => p.Logotype).Alias;
    var logotype = GetSiteSettings().GetProperty(logotypeAlias).GetValue() as Image;
    return logotype?.Url ?? string.Empty;

So by getting the property alias of the logotype that I wanted to display on the Settings Page, and finally get the value by casting the object to the specific Umbraco Image object, we may retrieve the url.

Worth mentioning is that you may also retrieve the properties down below with this method:
- UmbracoBytes
- UmbracoExtension
- UmbracoFile
- UmbracoHeight
- UmbracoWidth