Cleaner way to get parent node
t
Hi I have the below code public IPublishedContent GetPage(guid id) { var umbracoHelper = _umbracoHelperAccessor.TryGetUmbracoHelper(out var h); Return h.Content(id); } When I need a page I call GetPage(1234-5678-....) and the page is returned. This page could be 5 levels down. So the only way I'm able to get the parent is by writing something like GetPage(1234-5678-....).Parent.Parent.Parent Until I reach the homepage. That code looks ugly by adding multiple parents at the end of the GetPage function. Is there a better way to get the parent node for the site when using C#?
s
Copy code
csharp
_umbracoHelper.ContentAtRoot().FirstOrDefault();
is probably what you need
j
Also have a look at traversing the content tree: https://docs.umbraco.com/umbraco-cms/v/13.latest-lts/reference/templating/mvc/querying#traversing If you need to get a specific parent type and its not easier / better to do it top-down as Seb suggests, then you can call one of the ancestor methods with a type to go up the tree until you hit that type. Using modelsbuilder is very nice for this!
t
That did part of the trick..... It seems to only work if you have one site under Umbraco? If I have 2 sites it only brings the first in the node and not the one I'm currently browsing?
s
If the code is in a render controller, you can use the Current page as starting node and traverse from there. If it is in a view, you can use the umbracohelper.assignedcontent helper (or something like it). When trying to get it outside of either you can match on the culture. I hope this helps you along
t
It's in a custom class and for now I've injected the IUmbracoHelper only. I'm not sure what you mean that I could match on culture?
m
(Current IPublishedContent).AncestorOrSelf() will get you the ancestor of that content of type homepage
Assuming that HomePage is your models builder class 🙂
t
This did it!! Thanks
346 Views