Multiple items in a data source

Last updated Thursday, June 21, 2018 in Sitecore Experience Platform for Developer
Keywords: Development

This topic is valid for Sitecore 9, Update 2, and later.

You can specify a query in data source field of an MVC control, and this query can return multiple items. You access these items either in the controller code or in the view code.

For example, if you have a number of items named Sample Item 1, Sample Item 2, and so on, you specify the value of the Data Source property of a control as query: text: Sample Item* to retrieve all of these items.

The following example describes accessing the retrieved items:

Accessing items in the controller code

You use the RenderingContext.Current.Rendering.Items property to obtain a list of items:

using System.Web.Mvc;
using Sitecore.Data.Items;
using Sitecore.Mvc.Presentation;
namespace Sitecore.Mvc.Sample.Controllers
{
    public class UseItemsFieldController : Controller
    {
        public string Index()
        {
            string result = "";
            foreach (Item item in RenderingContext.Current.Rendering.Items)
            {
                result += $"</div>{item.Name}</div>";
            }
            return result;
        }
    }
}

Accessing items in the view code

You access the items in the view code in the following way:

@using Sitecore.Data.Items
@using Sitecore.Mvc.Presentation
<br>
<div>
    @foreach (Item item in RenderingContext.Current.Rendering.Items)
    {
        <div>@item.Name</div>
    }
</div>

Send feedback about the documentation to docsite@sitecore.net.