How to Create a Dynamic Multilist of Item Children and Loop Through It in Sitecore

One example of what we're trying to do here might be if you wanted to create a news page item with a feature that allows the content author to manually select multiple news items underneath it that are popular. The criteria is that the drop down list must only show items that are descendants of the news page item in question.

The trick to defining the allowed list data is to create a new Multilist field in the news page template and then defining the following fast query on that field:


query:.//*[@@templatename='News Article']

Here's how the field will look:

This gets all child items of the current item with the template name of whatever you want to specify. This will include children of children. To only get the immediate children, use / instead of //.

In the view, we can then iterate through the list items. Note that you'd probably want to cleanup this view code and move some of it outside of the view file:


Sitecore.Data.Fields.MultilistField multilistField = currentItem.Fields["Popular News Articles"];

if (multilistField != null && multilistField.TargetIDs.Any())
{
    <ul>
        @* Iterate over all the selected items by using the property TargetIDs *@
        @foreach (ID id in multilistField.TargetIDs)
        {
            Item targetItem = Sitecore.Context.Database.Items[id];
            <li><a href="@ViewHelper.GetUrl(targetItem)">@Html.Sitecore().Field("Title", targetItem)</a></li>
        }
    </ul>
}

Happy coding!

Marcel

Fish