14 September 2014

Retrieve Datasource from a Controller Rendering

If you are using Sitecore MVC then I am sure you have been using Controller Rendering. When using personlisation you are most likely either switch the Rendering or simply change the Datasource to point at different items. In your controller code, you may have tried the following:

SitecoreContext.GetCurrentItem< Item>()

With the SitecreContext being the Glass.Mapper.Sc.ISitecoreContext...

The GetCurrentItem in the controller will always return the Context Item, not the Datasource. So you need to actually retrieve the Datasource with Code. What you can use is something similar to:

        /// 
        /// Get either the data source or the context item
        /// 
        private Item Datasource
        {
            get
            {
                var dataSource = SitecoreContext.GetCurrentItem< Item>();
                string datasourceId = RenderingContext.Current.Rendering.DataSource;
                if (Sitecore.Data.ID.IsID(datasourceId))
                {
                    dataSource = SitecoreContext.GetItem< Item>(new Guid(datasourceId));
                }

                return dataSource;
            }
        }

From the above code you can see that this will either return the Context Item if the Datasource is not set, OR the datasource item if set.

Now, I am sure you will have to create multiple Controller Renderings in your solution. So it could be a great idea to create an abstract class Controller and all your controller will be based on this:

namespace MySite.Controllers
{
    public abstract class BaseController: SitecoreController
    {
        protected readonly ISitecoreContext BaseSitecoreContext;

        public BaseController(ISitecoreContext sitecoreContext)
        {
            this.BaseSitecoreContext = sitecoreContext;
        }

        /// 
        /// Get either the data source or the context item
        /// 
        public Item Datasource
        {
            get
            {
                var dataSource = BaseSitecoreContext.GetCurrentItem< Item>();
                string datasourceId = RenderingContext.Current.Rendering.DataSource;
                if (Sitecore.Data.ID.IsID(datasourceId))
                {
                    dataSource = BaseSitecoreContext.GetItem< Item>(new Guid(datasourceId));
                }

                return dataSource;
            }
        }
    }
}


You can now use the base Controller to derive your custom controller:
    public class CalculatorController : BaseController
    {
        private readonly ISitecoreContext sitecoreContext;

        public CalculatorController(ISitecoreContext sitecore)
            : base(sitecore)
        {
             // Do whatever
        }
    }

No comments:

Post a Comment