Copied to clipboard

Flag this post as spam?

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


  • Kasper Skov 6 posts 76 karma points
    Oct 26, 2016 @ 15:39
    Kasper Skov
    0

    Best practice getting ancestral root node with multiple root nodes

    I've been working with Umbraco for years and I sometimes have the feeling that i'm using the API in a wrong way. If you search google for "Umbraco get root" there's a million suggestions.

    In an UmbracoApiController or a SurfaceController, what's the right way to get the root node (the top ancestor) of the contextual current page with multiple root nodes of the same type present?

    No matter what the case is, these methods won't work:

    UmbracoHelper(UmbracoContext.Current).TypedContentSingleAtXPath("//root")
    

    Will get only the first node.

    UmbracoHelper(UmbracoContext.Current).TypedContentAtRoot();
    

    Will give you a list of all root nodes. No good.

    Case #1 - "ActionLink and SurfaceController":

    Lets say I would like to create a link that calls an action in a surface controller where I would need a property from the root node for what ever. In an ideal world, I would just write CurrentPage.AncestorOrSelf(0);. But CurrentPage is of course null. This would only work if I made a BeginForm from my view. That way UmbracoContext.PageId would also be exposed (I think). But I really want to do an ActionLink.

    The way I do it today is by passing the CurrentPage.Id or a model from the view, and then through ContentService in my SurfaceController I can find my ancestral root:

    Services.ContentService.GetAncestors(pageId).First();
    

    Is that really the way to it?

    Case #2 - "ApiController":

    The documentation says that the UmbracoHelper (through Umbraco) is exposed in an UmbracoApiController and that if you want the currently executing content item you can use UmbracoHelper.AssignedContentItem. Is that what i'm looking for here, if I want the "current page"? Or is it something entirely different? It always seems to be null in my controllers.

    Do I really need to pass parameters from my view and go through the ContentService as in case #1?

  • Sebastiaan Janssen 5045 posts 15476 karma points MVP admin hq
    Oct 27, 2016 @ 15:55
    Sebastiaan Janssen
    0

    Is that really the way to it?

    Definitely not. Unless you MUST have the version straight from the database. If you just want the published version then indeed Umbraco.AssignedContentItem is the current page - or even easier CurrentPage is the same thing!

    And of course Umbraco.TypedContentAtRoot() will work as well in your surfacecontroller.

Please Sign in or register to post replies

Write your reply to:

Draft