Search code examples
umbracotraversalchildren

Umbraco - Only Get Child Elements of an Document Type


I have a structure link below

PageOne

  • Columns

    -- ColumnItem-One

    -- ColumnItems-Two

    -- ColumnItems-Three

    -- ColumnItems-Four

PageTwo

  • Columns

    -- ColumnItems-OneB

    -- ColumnItems-TwoB

I have a partial view which I want to display each of the children Column items but at the moment I am using descendants which is returning all 6 items instead of 4 on PageOne and 2 on PageTwo.

My code is

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    var root = Model.Content;
    var tiles = root.Descendants("tiles");



    if(tiles.Count() > 0)
    {
        <div class="row tile-row">
            @foreach(var node in tiles)
            {
                <div class="col-md-3">
                    <div class="tile">
                        <h3>@(node.GetPropertyValue("tileTitle"))</h3>
                        @(node.GetPropertyValue("tileBodyText"))<br/>
                        <a class="btn btn-more" href="@(node.GetPropertyValue("tileButtonLink"))">@(node.GetPropertyValue("tileButtonText"))</a>
                    </div>  
                </div>
            }
        </div><!--/.row-->
    }
}

If I change descendants to Children() i get an error page.

Thansk


Solution

  • If you call the partial view from your PageOne or from your PageTwo, then you can do the following if you are using the strongly typed object:

    @inherits Umbraco.Web.Mvc.UmbracoTemplatePage
    @{
        // Get this PageOne or PageTwo object
        var page = Model.Content;
    
        // Get the column node that is descendant of this page
        var column = root.Descendants("columnAlias");
    
        // Get all children of the column node that are published
        var childs = column.Children.Where(x => x.IsVisible());
    
        if(childs.Count() > 0)
        {
            <div class="row tile-row">
                @foreach(var node in childs)
                {
                    <div class="col-md-3">
                        <div class="tile">
                            <h3>@(node.GetPropertyValue("tileTitle"))</h3>
                            @(node.GetPropertyValue("tileBodyText"))<br/>
                            <a class="btn btn-more" href="@(node.GetPropertyValue("tileButtonLink"))">@(node.GetPropertyValue("tileButtonText"))</a>
                        </div>  
                    </div>
                }
            </div><!--/.row-->
        }
    }