Computer Magic Logo
AncestorsOrSelf and Ancestors

Saturday, August 8, 2015

Published by Aristotelis Pitaridis

Sometimes we do not just want to get the single parent of a page but we want all the parent pages until we get to the top level page of our site. This can be done using the AncestorsOrSelf and Ancestors member functions which return an object of type System.Collections.Generic.IEnumerable<Umbraco.Core.Models.IPublishedContent>.

The difference between AncestorsOrSelf and Ancestors is that the Ancestors return an IEnumerable list with only the Ancestor pages but the AncestorsOrSelf returns an IEnumerable list which contains also the page which used as a reference. Let’s see some examples in order to understand what these member functions really do. We suppose that we have the following page structure.

Now we assume that we are in the path "/Page 2/Page 2, 1/Page 2, 1, 3" and we type the following code in our view.

@{
    var TypedItemsWithSelf = Model.Content.AncestorsOrSelf();
    var DynamicItemsWithSelf = CurrentPage.AncestorsOrSelf();
    var TypedItems = Model.Content.Ancestors();
    var DynamicItems = CurrentPage.Ancestors();
}
@TypedItemsWithSelf.Count()
@DynamicItemsWithSelf.Count()
@TypedItems.Count()
@DynamicItems.Count()

We wrote code so that we will get the ancestors with both member functions and for each member function we use dynamic and typed data types. After getting the information we just display the number of nodes we found for each of these queries. The output of the code above is the following.

3
3
2
2

We see that the AncestorsOrSelf returns 3 items and the Ancestors return 2 items. The AncestorsOrSelf returns the following list.

[0] = Page 2, 1, 3
[1] = Page 2, 1
[2] = Page 2

The Ancestors returns the following list.

[0] = Page 2, 1
[1] = Page 2

This means that if we want to display the name of the root page in the ancestors list we will have to type the following code.

@{
    var TypedItemsWithSelf = Model.Content.AncestorsOrSelf().ToList();
    var DynamicItemsWithSelf = CurrentPage.AncestorsOrSelf().ToList();
}
@TypedItemsWithSelf[TypedItemsWithSelf.Count() - 1].Name
@DynamicItemsWithSelf[DynamicItemsWithSelf.Count() - 1].Name

We used the ToList() member function in order to convert the IEnumerable to List of pages. The way we took the root page is quite complex because we use the index number of the element so we are going to use an easier way to find the page we want.

@{
    var TypedItemsWithSelf = Model.Content.AncestorsOrSelf();
    var DynamicItemsWithSelf = CurrentPage.AncestorsOrSelf();
}

@TypedItemsWithSelf.Last().Name
@TypedItemsWithSelf.First().Name

The Last() member function returns the last item in the list which is the ancestor at the root of the site and the First() member function return the first item in the list which is the current page.