How To Get Umbraco Root Node By Document Type in Razor Using Umbraco 7 Helper

If like us, you enjoy building great Umbraco websites, no doubt you've had the need on occasion to get a particular node from the root of the content tree. There are a number of ways to do this, one of the more common ones is to use something like:

var currentRoot = Model.Content.AncestorOrSelf(1);

However, this will only be able to get you the root node of the current tree. Suppose you had another tree (not in the path of the current node) in the root of Umbraco's content tree such as 'Site Settings'. How can you get this one without using Node Ids or other types of hard-coded references? Luckily, one of the helper methods will prove quite useful. On Umbraco's helper object, you can call:


Which will actually return a collection of all nodes in the root of your content tree, irrespective of path and tree structure.  It may not be obvious why this is incredibly useful, so let's suppose you had a node with a document type alias of 'SiteSettings' from anywhere in Umbraco's content on your site you can do:

var siteSettings= Umbraco.TypedContentAtRoot().FirstOrDefault(x => x.ContentType.Alias.Equals("SiteSettings")); 

This will return the first node (if it exists) in the root of Umbraco's content tree which has the document type of "SiteSettings". If no such node of this type exists in Umbraco's root, then the value of the siteSettings variable will be null. It's important to note that by including either .First() or .FirstOrDefault() at the start of your query, this will likely be more efficient than doing either of these at the end of your query like so:

var siteSettings= Umbraco.TypedContentAtRoot()
.Where(x => x.ContentType.Alias.Equals("SiteSettings")).FirstOrDefault();

Taking the First or Default at the end, basically means you gether nodes you discard in the next step which is wasteful, and can lead to a new possibility of a null reference exception if indeed the initial query returns no nodes.

From experience, we have also noted that some of these queries can be quite costly on the servers time and resources. If you find many queries of this kind in each page, it would be worth considering storing these values for later use either in a caching layer or by holding in memory of the application for re-use, without needing to re-run this lookup. If you do this, we recommend then being sure to attach an event to Umbraco publish to invalidate the cache where needed (i.e. if the updated nodes affect the query, your application should re-run this query and update it's cache.

We will discuss some of these topics later in more detail and build on some of these ideas, but hopefully these will prove useful.


Need an Umbraco Master?

Here at Simon Antony, we have an in house certified Umbraco Grand Master available for hire. Got a problem with your site, need architecture advice, give us a call to speak to Simon directly and see how we can help

Contact Simon Today!