Reading Datasource and Presentation Parameters from a user control in Sitecore


Sitecore allows you to pass a Datasource and Presentation Parameters to a user control via the UI but it’s wasn’t really clear how to read them from a user control.  If you take a Sitecore Certified Developer course this is now covered but before that I had to dig through forum posts to figure out how to do this so I thought I’d share the code I use for reading this information.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Collections.Specialized;

namespace Sitecore.Prototypes.WebControls
{
    public class BaseUserControl : UserControl
    {
       string datasource = null;
        Item item;

        NameValueCollection parameters = null;

        public Item DataItem
        {
            get
            {
                if (item == null)
                {
                    if (string.IsNullOrEmpty(this.DataSource))
                    {
                        item = Sitecore.Context.Item;
                    }
                    else
                    {
                        item = Sitecore.Context.Database.SelectSingleItem(this.DataSource);
                    }
                }
                return item;
            }
        }


        public string DataSource
        {
            get
            {
                if (datasource == null)
                {
                    if (this.Parent is Sitecore.Web.UI.WebControls.Sublayout)
                    {
                        datasource = ((Sitecore.Web.UI.WebControls.Sublayout)this.Parent).DataSource;
                    }
                    if (datasource == null) { datasource = string.Empty; }
                }
                return datasource;

            }

            set { datasource = value; }
        }

        public string GetParameter(string parameterKey)
        {
            string value = string.Empty;
            if (parameters == null)
            {
                string rawParameters = Attributes["sc_parameters"];
                parameters = Sitecore.Web.WebUtil.ParseUrlParameters(rawParameters);
            }

            if (parameters[parameterKey] != null)
                value = HttpUtility.UrlDecode(parameters[parameterKey].ToString());
            return value;
        }
    }
}

Advertisements