Multiple items in a data source
Abstract
You can specify a query as the data source of an MVC control
Note
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:
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; } } }
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>