How do you get the Sitecore Sublayout from a Usercontrol? A Sitecore Sublayout (Sitecore.Web.UI.WebControls.Sublayout) is a container for your Usercontrol (.ascx) page. Therefore the Sublayout is retrieved by typecasting the parent to a Sublayout:
using Sitecore.Web.UI.WebControls; Sublayout thisSublayout = (Parent as Sublayout);
Having the Sublayout in hand enables you to read the Sublayout data, for example the “datasource” field. The datasource field can be used to alter which item the Sublayout should render. You can apply a datasource to your sublayout directly, telling the userControl (.aspx page) to render a different item than the current item (Sitecore.Context.Item).
In one of my recent projects (for Sitecore Foundry, but the code works for Sitecore 5 and Sitecore 6 as well) I inherited from this base class instead of the System.Web.UI.UserControl. The class is very simple. It gives me the Sitecore item as stated in the datasource, or the current item if the datasource item is not set:
using Sitecore.Data.Items;
using Sitecore.Web.UI.WebControls;
namespace MyProject.MyNameSpace
{
/// <summary>
/// This class contains the CurrentContextItem function
/// which allows the system to use
/// the datasource property on sublayouts.
/// </summary>
public class SublayoutBaseClass : System.Web.UI.UserControl
{
/// <summary>
/// Gets the current context item.
/// </summary>
/// <value>The current context item.</value>
protected Item CurrentContextItem
{
get
{
Sublayout thisSublayout = (Parent as Sublayout);
if (thisSublayout == null)
return Sitecore.Context.Item;
if (string.IsNullOrEmpty(thisSublayout.DataSource))
return Sitecore.Context.Item;
string dataSource = thisSublayout.DataSource;
Item dataSourceItem = Sitecore.Context.Database.GetItem(dataSource) ??
Sitecore.Context.ContentDatabase.GetItem(dataSource);
if (dataSourceItem == null)
return Sitecore.Context.Item;
return dataSourceItem;
}
}
}
}
