Tag: Sublayouts

Sitecore: Data binding to a datasource rather than the context

By default when you place a Sitecore control. e.g. on a page it will bind to the pages context item even if the rendering has had a Data Source set against it.

MVC - View Renderings

If your Sitecore solution is MVC based and you are using a View Rendering then this is simple. Make sure your view's model is set to Sitecore.Mvc.Presentation.RenderingModel and then pass Model.Item as the item parameter to the Sitecore HTML helper function for rendering a field.

1@using Sitecore.Mvc
2@using Sitecore.Mvc.Presentation
3
4@model Sitecore.Mvc.Presentation.RenderingModel
5
6<div>
7 <h2>@Html.Sitecore().Field("Title", Model.Item)</h2>
8 <div>@Html.Sitecore().Field("Content", Model.Item)</div>
9</div>

WebForms - Sublayouts

However if your Sitecore solution is using WebForms with sub-layouts then thing's get a little trickier. Unlike with the View Rendering there is no equivalent of Model.Item so a bit of work is required to get the Data Source Item.

If you check to see if the controls parent is a sublayout, you can then cast it as a sublayout and access the datasource property from their. You will then need to set the Item property of each of the Sitecore Controls in your sublayout. In this example the Sitecore Control is being referenced by controlled in the code.

1Item DataSource;
2if (Parent is Sublayout)
3 DataSource = Sitecore.Context.Database.GetItem(((Sublayout)Parent).DataSource);
4
5controlId.Item = DataSource;