Search code examples
umbraco

Get Image ID of Child Item


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'm trying to use best practice by using strongly-typed models and 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?

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"/>
}

For info, I've enabled AppData ModelsMode and rebuilt the models. 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");


Solution

  • This was solved on the Umbraco forums so I'll post the answer here.

    With Umbraco strongly-typed models you can pass the value inline to the html tag, e.g.:

    <img src="@location.LocationImage.Url"/>
    

    Instead of having to pass it to a service.