Attempt to read an added "Related Media" (Image) field on news items causes error in MVC template - Front- & Back-End Development - Front- & Back-End Development - Progress Community
 Front- & Back-End Development

Attempt to read an added "Related Media" (Image) field on news items causes error in MVC template

  • Attempt to read an added "Related Media" (Image) field on news items causes error in MVC template
  • I need to add an image to news, separate from the content.

    To achieve this, I added a field of type "Related media (images, videos, files)" to the News data fields, named it "Image", and set it up as a single selectable image, to use the image selector widget and render as simple link.

    In the code, I access the field:

     

                        if (!String.IsNullOrWhiteSpace(item.Fields.Image.Fields.MediaUrl))
                       
                            <img src="@Html.Raw(item.Fields.Image.Fields.MediaUrl)">
                       

    as  this worked perfectly on List items. I also tried

                        if (!String.IsNullOrWhiteSpace(item.RelatedItem("Image").Fields.MediaUrl))
                       
                            <img src="@Html.Raw(item.RelatedItem("Image").Fields.MediaUrl)">
                       

    I get a RuntimeBinderException ("Cannot perform runtime binding on a null reference"), or a NullReferenceException respectively. Guessed a spelling error and checked multiple times, to no avail. What am I doing wrong?

     

    Edit: Forgot to mention that the view renders with  no problems with the concerned code lines removed.

  • This was a case of tunnel vision. I assumed, the property, since registred, would be created, even if not set. At least I would have done so. In fact, this is not the case, so 
    String.IsNullOrWhiteSpace(item.Fields.Image.Fields.MediaUrl)
    fails when no image is set.

    the code to use here is 
     @if(item.RelatedItem("Image") != null)

    ...