Multiple items in a data source

Current version: 10.1
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 1Sample 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:

RequestResponse
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:

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

Do you have some feedback for us?

If you have suggestions for improving this article,