Dynamic items

Sometimes you might not want to create a model, you might just want to render data quickly. This is where the dynamic keyword support comes in. The dynamic support allows you to pull data directly from Sitecore without a model, the easiest way to explain this is to see it in action.

I have created a new sublayout called Metadata which will be used to contain the data I want to rendering in the head section of the page. The code behind for the sublayout uses the GlassUserControl but takes the dynamic type as the model type:

using Glass.Mapper.Sc.Web.Ui;

namespace Glass.Mapper.Sites.Sc.layouts.Site.Misc
{
    public partial class Metadata : GlassUserControl<dynamic>
    {

    }
}

My ascx markup looks like this:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Metadata.ascx.cs" Inherits="Glass.Mapper.Sites.Sc.layouts.Site.Misc.Metadata" %>

<title><%=Model.Title %></title>

<link rel="canonical" href="http://sitecore.glass.com<%=Model.Url %>" />
<link rel="prev" href="http://sitecore.glass.com<%=Model.Parent.Url %>" />

<% foreach (var child in Model.Children)
   { %>
<link rel="next" href="http://sitecore.glass.com<%=child.Url %>"/>
<% } %>

<meta name="updated" content="<%=Model.__updated %>" />


In the markup you can see we are pulling the items Title and the Updated fields. To render these fields in the background they are sent through the FieldRender control, you don't have to worry about this but it does mean that Rich Text fields will have links updated correctly.

Next we set the canonical Url by calling the Url property, this will return the items Url. There are a set of reserved property names that allow you to retrieve information about an item, the name match the enum values in the Glass.Mapper.Sc.Configuration.SitecoreInfoType type.

The dynamic item also supports navigating up and down the tree by using the Parent and Children properties. The Parent property will return another dynamic type and the Children property will return an IEnumerable<dynamic>.

If we look at the source of our page the metadata is rendered with minimal effort and without a strongly typed model.

    <title>Events</title>

    <metadata name="updated" content="03/03/2013 11:39:56" />

    <link rel="canonical" href="http://sitecore.glass.com/Events.aspx" />

    <link rel="prev" href="http://sitecore.glass.com/" />


    <link rel="next" href="http://sitecore.glass.com/Events/2013.aspx"/>

Dynamic items are great for getting data out of Sitecore with minimal effort.