Search code examples
umbracoumbraco7

Accesing the content from immediate parent in Umbraco


I am trying to access content from my level 2 document type from a sub level in Umbraco. level 2 has multiple pages of same document type. I am using the code below

var rootByTraversing = Umbraco.AssignedContentItem.AncestorOrSelf(2);
var openingTimesByDescendants = rootByTraversing.Descendants().Where(f => f.DocumentTypeAlias == "PageLevel2").FirstOrDefault();

Is it possible for me to get the immediate parent node of this document type and not FirstOrDefault node? I don't want to access the content through node id.


Solution

  • Not sure I follow entirely, especially why you don't want to access via node ID... Your current content item has a Path property in which all ancestors IDs are listed in a comma separated list. Couldn't you just split that string and select whichever level (like ancestors[2] for level 2, I'd guess) to get the ID of that node. Then you could go something like

    var level2AncestorId = Umbraco.AssignedContentItem.Path.Split(',')[2];
    var openingTimesByDescendants = rootByTraversing.Descendants().Where(f => f.Id == (int)level2AncestorId && f.DocumentTypeAlias == "PageLevel2").FirstOrDefault();
    

    Which should only give you one node and it should be the direct ancestor. Right?