Search code examples
umbracoumbraco7

Umbraco 7 Archetype unable to get media udi


I have read these posts

https://our.umbraco.org/forum/templates-partial-views-and-macros/85993-archetype-mediapicker-udi

https://our.umbraco.org/forum/using-umbraco-and-getting-started/85598-getting-image-url-from-media-picker-not-working-in-76

http://www.codeshare.co.uk/blog/how-to-get-the-file-path-of-a-media-item-in-umbraco/

but I'm still unable to get the value from the media picker.

On my last attempt, I got the following error.

Object reference not set to an instance of an object

If I try the following:

string img = "";
            foreach (var d in archtypePanel.Properties)
            {
                if (d.Alias == "imageToDisplay")
                {
                    img = d.Value.ToString();
                }
            }

I can see the media UDI: "umb://media/15cc14d318f3444a86ab3bc7fc5787ad" but I'm unable to get any further.

I have now run into a wall, so any help on solving this issue will be helpful.

My last attempt is below:

Guid idValue = new Guid(id);
            var blogPosts = CurrentPage;
            IPublishedContent blogPosts2 = CurrentPage;
            var archtypePanel = blogPosts2.GetPropertyValue<ArchetypeModel>("blogArchetypes").First(x=>x.Id == idValue);

            ArchetypeWithTextAndImageModel model = new ArchetypeWithTextAndImageModel
            {
                TextContent = new HtmlString(archtypePanel.GetValue("textRichTextEditor")),
                ImageId     = archtypePanel.GetValue<IEnumerable<IPublishedContent>>("imageToDisplay").ToString()// imgUrl
            };

But ImageId throws the error.


Solution

  • Access from strong type model

    make sure your Umbraco-Core-Property-Value-Converters is updated to latest

    and also in umbracoSettings.config <EnablePropertyValueConverters>true</EnablePropertyValueConverters> is set to true

    then access your media url via
    archtypePanel.GetPropertyValue<IPublishedContent>("imageToDisplay").Url

    Access using udi url

    another way is by using the udi url you have got and get media like:

    // Your string which is retrieved from Archetype.
    var imageString = "umb://media/c33bfe07a82b4df18a79db154139cb91";
    
    // Get the guid from this string.
    var imageGuidUdi = GuidUdi.Parse(imageString);
    
    // Get the ID of the node!
    var imageNodeId = ApplicationContext.Current.Services.EntityService.GetIdForKey(guidUdi.Guid, (UmbracoObjectTypes)Enum.Parse(typeof(UmbracoObjectTypes), guidUdi.EntityType, true));
    
    // Finally, get the node.
    var imageNode = Umbraco.TypedMedia(imageNodeId.Result);
    

    more info about this, checkout Umbaco Archtype rendering images (MediaPicker2)