Using a custom data source for Sitecore MVC renderings

June 26 2013

Glass provides a mapper over your sitecore content items, providing a strongly typed ORM.  Using MVC view renderings it’s trivial to build pages using Glass.Mapper.Sc and inheriting your view from GlassView<TGlassModel>, where TGlassModel is a class mapped by Glass. 

In Sitecore you can build your presentation view by composing various renderings for the current item.  Rather than use the current page item as the source of the data for the rendering (as is the default when no explicit data source is supplied), you can manually select an item from the content tree to act as data source (in sitecore 7 you can use search queries too and multiple items).   Normally you set the the data source per rendering and per page, although you could set it in the standard values of the template if you require a default.

Using the standard Glass mapped classes, the model doesn’t know about the manually data source .  I expect you can get funky customising the renderModel pipeline but there’s a quicker way.  Use a controller rendering.

Using a controller rendering, you can call the introduced-with-mvc RenderingContext.Current.Rendering.DataSource property to get the data source for the current rendering.

A simple controller action would look like this

public ActionResult FeaturedPackage()
    var package = SitecoreContext.GetItem<Package>(RenderingContext.Current.Rendering.DataSource);

    return View("_FeaturedPackage", package);

and on the specific implementation of the controller rendering I’ve selected the appropriate content item from the tree.  This has populated the renderings DataSource field with a GUID.  The GUID is returned as a string by the call to RenderingContext and Glass's GetItem takes a string as param. Perfect!


Now my rendering retrieves the data from items set in the data source field, allowing me to build a page that has three “FeaturePackage” controller renderings


Post a comment

comments powered by Disqus