Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Luis Pedro Pereira 13 posts 93 karma points
    Nov 13, 2018 @ 08:31
    Luis Pedro Pereira
    0

    Iterate trough all images in a Media folder

    Hi all.

    How can I iterate trough all images/objects existing inside one predefined media folder?

    BR /LPP

  • Dan Diplo 1554 posts 6205 karma points MVP 5x c-trib
    Nov 13, 2018 @ 10:35
    Dan Diplo
    0

    It's basically the same way you would handle content. So once you have a reference to the folder, you can call Children() to get it's immediate children or Descendants() to get all items in the folder, however nested (this might bring back other folders, too).

    eg.

    var folder = Umbraco.TypedMedia(1234);
    var allMedia = folder.Descendants();
    

    Or to get all descendant media that is NOT a folder you can do:

    var media = folder.Descendants().Where(f => f.DocumentTypeAlias != global::Umbraco.Core.Constants.Conventions.MediaTypes.Folder);
    
  • Luis Pedro Pereira 13 posts 93 karma points
    Nov 13, 2018 @ 11:26
    Luis Pedro Pereira
    0

    But where can I use this logic?

    Because I'm using it on a SurfaceController, I'm 100% positive that there's media images inside the folder, and the foreach is broken immediately, altough .Descendants() are not null.

    Here's my usage:

            var folderId = 1234;
            var folder = Umbraco.TypedMedia(folderId);
            var allMedia = folder.Descendants();
            foreach(var media in allMedia)
            {
                listOfAllUrls.Add(media.Url);
            }
    

    Actualy, 'allMedia.Current' is null but not 'allMedia'

    Note: Same result with the 2nd approach.

  • Dan Diplo 1554 posts 6205 karma points MVP 5x c-trib
    Nov 13, 2018 @ 13:13
    Dan Diplo
    0

    You can use the logic in a controller or a view - the principle is the same.

    You probably need to do a null check to ensure that folder exists, and maybe also check if it's a folder type? Are you sure the Id is correct? Check for the ID in the Umbraco Media tree.

    if (folder != null)
    {
        var allMedia = folder.Descendants();
        foreach (var media in allMedia)
        {
            //...
        }
    }
    

    But that code will definitely work. Presumably you have a List<string> called listOfAllUrls that you are adding this media to? (Though it would be simpler just to use folder.Descendants().Select(x => x.Url).ToList() to do that.

    Also, make sure you have included the using Umbraco.Web namespace.

Please Sign in or register to post replies

Write your reply to:

Draft