Friday, May 15, 2015

Sitecore Query in the MVC Rendering Datasource

I found many articles about resolving queries for the ASP.NET Webforms and nothing for the MVC. Sitecore doesn't support it OOTB, so I decide to write this small post.
First of all we need to create a new processor in the Sitecore pipeline:

using Sitecore.Data.Items;
using Sitecore.Mvc.Pipelines.Response.RenderRendering;
namespace CustomSolution.Common.Pipelines
    public class RenderingDatasourceQueryResolver : RenderRenderingProcessor
        public override void Process(RenderRenderingArgs args)
            string dataSource = args.Rendering.DataSource;
            if (!dataSource.StartsWith("query:")) return;
            Item queryItem = args.PageContext.Item.Axes.SelectSingleItem(dataSource.Substring(6));
            if (queryItem != null)
                args.Rendering.DataSource = queryItem.Paths.FullPath;

Now we needs to register the Processor:

     <processor patch:before="*[@type='Sitecore.Mvc.Pipelines.Response.RenderRendering.ExecuteRenderer, Sitecore.Mvc']"  
       type="CustomSolution.Common.Pipelines.RenderingDatasourceQueryResolver, CustomSolution"/>  

Now we can use a Sitecore query, for example to get the Site:

That is it! 

No comments:

Post a Comment