Get Context Item

Get Context Item

The Context Item

  • A type of context object that corresponds to the requested URL
  • Is the default data source for all renderings for which the developer does not specify a data source
  • Contains many more properties that provide access to:
    • Database associated with the current site
    • User authenticated user who made the request
    • The raw URL requested

Controls featured in this example:

  • Sitecore Web Control

Classes featured in this example:

  • Sitecore.Context
  • Sitecore.Data.Items.Item

Context Item C# Web Control Code

Sitecore.Data.Items.Item item = Sitecore.Context.Item;
if (item == null) return;

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.Write("C# Web Control Real-time Output");
output.RenderEndTag();

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-size:x-small; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
//using : for colon and   for space
output.Write("{0}: {1}", "Item", item.DisplayName);
output.RenderEndTag(); //P

if (item.Appearance.Icon != null)
    output.Write("{0}&#58;&#160;{1}", "Item Icon", "<b>" + item.Appearance.Icon + "</b><br/>");
if (Sitecore.Context.Item.Appearance.Style != null)
    output.Write("{0}&#58;&#160;{1}", "Item Style", "<b>" + item.Appearance.Style + "</b><br/>");
if (item.Appearance.ShortDescription != null)
    output.Write("{0}&#58;&#160;{1}", "Item Short Description", "<b>" + item.Appearance.ShortDescription + "</b><br/>");
if (item.Appearance.LongDescription != null)
    output.Write("{0}&#58;&#160;{1}", "Item Long Description", "<b>" + item.Appearance.LongDescription + "</b><br/>");
if (Sitecore.Context.Item.Appearance.Ribbon != null)
    output.Write("{0}&#58;&#160;{1}", "Item Ribbon", "<b>" + item.Appearance.Ribbon + "</b><br/>");

//int values (not null) 
output.Write("{0}&#58;&#160;{1}", "Item Sortorder", "<b>" + item.Appearance.Sortorder.ToString() + "</b><br/>");

//boolean values (not null) - using &#63; for question mark and &#160; for space 
output.Write("{0}&#63;&#160;{1}", "Item Hidden", "<b>" + item.Appearance.Hidden.ToString() + "</b><br/>");
output.Write("{0}&#63;&#160;{1}", "Item ReadOnly", "<b>" + item.Appearance.ReadOnly.ToString() + "</b>");

output.RenderEndTag(); //Div


Context Item C# Web Control Output

Item Icon: Software/32x32/text_code_colored.png
Item Style: 
Item Short Description: 
Item Long Description: 
Item Ribbon: 
Item Sortorder: 100
Item Hidden? False
Item ReadOnly? False

Notes

  • Sitecore.Data.Items.Item item = Sitecore.Context.Item; //valid in user controls and web controls
  • Sitecore.Data.Items.Item item = this.GetItem(); //valid in web controls