Friday, May 15, 2015

Resolving old legacy URL’s with Sitecore

This summary is not available. Please click here to view the post.

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:

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


Now we can use a Sitecore query, for example to get the Site:
query:./ancestor-or-self::*[@@templatename='Site']


That is it!