Wednesday, December 10, 2014

Global DataSource Base Class for Sitecore Controls

One of the things I started to do in Sitecore development is to utilize a common base class for all .ascx's that utilize a "global data source".  By global data source, I'm talking about data that lives outside of the page template.  This has many uses, such as when you have content that should be common across pages (header / footer maybe?), or any controls that display one-to-many relationship type data.

public class BaseGlobalDataControl : System.Web.UI.UserControl
{
        private Item _dataSource;
        public Item DataSource
        {
            get
            {
                if (_dataSource == null)
                {
                    var parent = Parent as Sublayout;
                    if (parent != null)
                        _dataSource = Sitecore.Context.Database.GetItem(parent.DataSource);
                }

                return _dataSource;
            }
        }
 }

Then on my child ascx's, the DataSource is used as the main data item that drives the control.  Very useful, and a very simple way to use inheritance in Sitecore development.

No comments:

Post a Comment