OrchardCMS / OrchardCore

Orchard Core is an open-source modular and multi-tenant application framework built with ASP.NET Core, and a content management system (CMS) built on top of that framework.
https://orchardcore.net
BSD 3-Clause "New" or "Revised" License
7.45k stars 2.41k forks source link

GetAnchors() is null #13133

Open scleaver opened 1 year ago

scleaver commented 1 year ago

Describe the bug

GetAnchors() always seems to be null when you have extracted a MediaField from a ContentItem.

To Reproduce

ContentItem contentItem = Model.ContentItem;

// Method 1 - from part model
var episodePart = contentItem.As<EpisodePart>();
MediaField artworkField = episodePart.Artwork;
Anchor[] anchors1 = artworkField.GetAnchors(); // null

// Method 2 - using ToObject on the dynamic representation of the field
MediaField artworkField2 = (MediaField)Model.ContentItem.Content.EpisodePart.Artwork?.ToObject<MediaField>();
Anchor[] anchors2 = artworkField2.GetAnchors(); // null

// Method 3 - using ToObject on the dynamic representation the anchors
Anchor[] anchors3 = (Anchor[])Model.ContentItem.Content.EpisodePart.Artwork.Anchors?.ToObject<Anchor[]>(); // works

Expected behavior

I would expect to see GetAnchors() working in cases 1 & 2 - perhaps I am doing something wrong?

Skrypt commented 1 year ago

Take a look at the Content data of your ContentItem. This is what that GetAnchors method does:

        /// <summary>
        /// Anchors are a less well known property of a media field.
        /// </summary>
        public static Anchor[] GetAnchors(this MediaField mediaField)
        {
            var anchors = mediaField.Content["Anchors"] as JArray;

            return anchors != null ? anchors.ToObject<Anchor[]>() : Array.Empty<Anchor>();
        }

You need to take a look at the contentItem before doing contentItem.As<EpisodePart>(); and compare if the MediaField.Content is there. Else, it looks like a bug.