Passing Parameters to a Sitecore MVC ItemRendering

26 March 2016

A recent question from fellow Sitecore MVP Jason St-Cyr and this question on StackOverflow prompted me to investigate how to pass parameters from a parent rendering to an item rendering.

The simplest way to call an ItemRendering is like this:


To pass a value to the item renderings we should be able to use something like this:

@Html.Sitecore().ItemRendering(item, new { Message = "Hello World" })

and then in our child rendering, use the following to access the value passed in the parent rendering:

@Html.Sitecore().CurrentRendering.Properties["Message"] //cshtml
RenderingContext.Current.Rendering.Properties["Message"] //controller code

Unfortunately due to a bug (or feature?) in Sitecore this does not work correctly.

Work around

One of the things I like about Sitecore MVC is the great flexibility you have in the presentation API and fortunately there is another method, @Html.Sitecore().Rendering() which we can use instead. It takes the ID (or path) of the rendering definition item and a parameters argument where a datasource can be set. Because the datasource item must have its __Renderers field set to a rendering ID to work as an ItemRendering, we can read this and pass it to the Rendering() method as shown below:

    new {
        Datasource = item.ID, 
        Message = "Hello World"

Hopefully this will be useful to someone. If you have any comments, questions or suggestions, feel free to leave a comment below!

Tags: Sitecore APISitecore MVC
comments powered by Disqus