Get Image ID of Child Item (strongly typed)

Hi.

I’m trying to get the ID of a child item’s image property so I can use Umbraco.Media() to display the image.

I have two doctypes Locations (parent) and Location (child).

I’m using v8 and trying to use best practice by using strongly-typed models. I think I’ve called the strongly-typed models correctly here.

Why is the following code returning the ‘Object reference not set to an instance of an object’ error at the ‘var imageId = location.LocationImage.Id;’ line?

What’s wrong with my syntax? (for info, Umbraco.TypedMedia is now deprecated and my intellisense doesn’t provide GetPropertyValue).

Thank you.

@inherits Umbraco.Web.Mvc.UmbracoViewPage<ContentModels.Locations>
@using ContentModels = Umbraco.Web.PublishedModels;

@{
    Layout = "master.cshtml";
    var locations = Model.Children<Location>();
}

@foreach (var location in locations)
{
    <p>@location.LocationName</p> //this returns a string as expected

    var imageId = location.LocationImage.Id; //this throws the error

    var image = Umbraco.Media(imageId);
    <img src="@image"/>
}

Location.LocationImage isn’t null…

if (location.LocationImage != null)
{
	<p>@location.LocationImage</p>
}

…returns the string ‘Umbraco.Web.PublishedModels.Image’.

I’ve enabled AppData ModelsMode and rebuilt the models: For info, the implementation in my Location.generated.cs is:

/// Location Image [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.0.4")] [ImplementPropertyType("locationImage")]
public Image LocationImage => this.Value("locationImage");

Arrrgh! :slight_smile:


This is a companion discussion topic for the original entry at https://our.umbraco.com/forum/96878-get-image-id-of-child-item-strongly-typed