Atom
Atom

Reputation: 340

Umbraco - Finding Root Node in C#

I'm working on a backend module, so Node.GetCurrent() is not an option. I need to find a way to call something like Node currentNode = new Node(parentNodeId); and get the root node of the site. I've seen samples in XSLT, but nothing for C#. Does anyone know how I can accomplish this?

Even just getting the ID of the root node so I can call new Node() would be great.

Upvotes: 14

Views: 26924

Answers (6)

Gcamara14
Gcamara14

Reputation: 538

I frequently use this one. I like that it's relative so that if you have multiple root nodes you can target both without a foreach loop.

IPublishedContent topNode = Model.Content.AncestorOrSelf(1);

Upvotes: 0

Leszek P
Leszek P

Reputation: 1866

Umbraco 7:

Umbraco.TypedContentAtRoot();

Upvotes: 5

tryinHard
tryinHard

Reputation: 576

Update for Umbraco 7 (may work in earlier versions too)

@{
    var siteroot = CurrentPage.AncestorOrSelf(1);
}

For further info, check out the documentation -> http://our.umbraco.org/Documentation/Reference/Querying/DynamicNode/Collections

Upvotes: 10

tcmorris
tcmorris

Reputation: 334

Update for Umbraco 6+

public static IPublishedContent GetRootNode()
{
    var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
    var rootNode = umbracoHelper.TypedContentSingleAtXPath("//root"));

    return rootNode;
}

This just takes a document type alias and finds the root node as IPublishedContent using the current Umbraco context. UmbracoHelper gives you quite a few options off this also.

Upvotes: 6

DotNetDan
DotNetDan

Reputation: 76

Brennan is correct,

var rootNode = new DynamicNode(-1);

works as well!

Upvotes: 5

E.J. Brennan
E.J. Brennan

Reputation: 46839

The rootnode is always available as:

var rootNode = new Node(-1);

Upvotes: 15

Related Questions