Menu

Query Umbraco Nodes with Different Document Types

December 30, 2014 by Christopher Sherman

Querying for child content of Umbraco document types is a straightforward process on Razor templates that inherit from UmbracoTemplatePage, but querying for content from different document types is more opaque. Displaying content from areas throughout a website is common on views such as home pages, so in this tutorial I’ll show you how you can utilize Razor and XPath to grab content from disparate document types.

XPath is a standard for navigating through elements in an XML document. You can find out more about XPath on the Mozilla Developer Network. We’ll use XPath to grab a reference to an Umbraco document type of type Portfolio.

Once you have a reference to the content node, you can use an Umbraco method to grab the specific node. Then query children of that node as you normally would if you were on the same template as that node. See the code sample below for implementation details.

@inherits Umbraco.Web.Mvc.Umbraco.Web.Mvc.UmbracoTemplatePage
@{
Layout = "Layout.cshtml";
}

@{
// Query for the Portfolio document type. Since this is a parent type, query for a single.
var projectNodeReference = Umbraco.TypedContentSingleAtXPath("//Portfolio");

    if (projectNodeReference != null)
    {
        // Get the Portfolio node object by Id.
        var projectNode = Umbraco.Content(projectNodeReference.Id);




        <ul>
            @foreach (var item in projectNode.Children.Where("Visible").OrderBy("CreateDate desc"))
            {
                <li>
                    <a href="@item.Url">
                        <div>
                            <img src="@item.image" alt="@item.Headline screenshot">
                            <div>
                                <p>
                                    @item.Headline
                                </p>
                            </div>
                        </div>
                    </a>
                </li>
            }
        </ul>
    }

}

Umbraco Razor