Join us this Friday for AI in Action at the Virtual Happy Hour! This free virtual event is open to all—enroll now on Academy and don’t miss out.

 

How to use GetParetns from CurrentPage

Vote:
 

How do I get all the parents of my CurrentPage? How do I use GetParents with Model.CurrentPage?

#148399
May 12, 2016 0:06
Vote:
 

Maybe you could simply iterate using ParentLink reference.

Here is the extension method snippet:

using System.Collections.Generic;
using System.Linq;
using EPiServer;
using EPiServer.Core;

namespace ContentAreaWithPreview.Business
{
    public static class ContentLoaderExtensions
    {
        public static IEnumerable<IContent> GetAllParents(this IContentLoader contentLoader, ContentReference contentReference)
        {
            if (ContentReference.IsNullOrEmpty(contentReference))
            {
                return Enumerable.Empty<IContent>();
            }
            contentReference = contentLoader.Get<IContent>(contentReference).ParentLink;

            var contentReferences = new List<IContent>();
            while (!ContentReference.IsNullOrEmpty(contentReference))
            {
                var content = contentLoader.Get<IContent>(contentReference);
                contentReferences.Add(content);

                contentReference = content.ParentLink;
            }
            return contentReferences;
        }
    }
}

and using the method in code:

 ContentReference cr = new ContentReference(1234);

var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();

contentRepository.GetAllParents(cr);
contentLoader.GetAllParents(cr);
#148406
May 12, 2016 8:03
Vote:
 
_contentLoader.GetAncestors(currentPage.ContentLink)
#148410
May 12, 2016 8:32
Vote:
 

You could also simply use GetAncestors:

IEnumerable<IContent> ancestors = contentRepository.GetAncestors(currentPage.ContentLink);

Edit: Gayathri beat me to it :-)  

#148411
Edited, May 12, 2016 8:34
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.