Andrés Villenas

Software Engineering, .Net Development, Sitecore, and more fun.

How to create custom view rendering

According to the Sitecore community documentation, "a view rendering is the simplest Sitecore MVC rendering type. As with all presentation items in Sitecore, a view rendering consists of a definition item in Sitecore and a file on the file system." 

By default, the view rendering will have access to the current page. The .cshtml view has to use the RenderingModel class as the default model. The view can look like this:

@using Sitecore.Mvc
@using Sitecore.Mvc.Presentation
@model RenderingModel

<div>
  <p>FieldValue: @Model.Item["FieldName"]</p>
</div>

As this approach might work for several cases, there may be other cases where a custom model is required. Also, custom models would be useful to avoid hardcoded values of the field names or processing in the .cshtml view. 

So, to create a custom view rendering, follow the next steps:

1. Custom rendering model class

The custom class should implement the IRenderingModel interface. 

using Sitecore.Mvc.Presentation;

namespace ProjectX.Views.Renderings
{
    public class CustomRenderingModel : IRenderingModel
    {
        // Use field id instead of the name to avoid issues if it is changed.
        private readonly ID FieldId = new ID("{3BA5E416-BC8E-4CEB-9D51-7E246E1C0B73}"); 

        public Rendering Rendering { get; set; }
        public Item Item { get; set; }
        public Item PageItem { get; set; }

        public void Initialize(Rendering rendering)
        {
            Rendering = rendering;
            Item = rendering.Item;
            PageItem = PageContext.Current.Item;
        }

        public string FieldValue
        {
             get { return Item[FieldId] }
        }
    }
}

2. Modify the .cshtml view to use the custom model

@using Sitecore.Mvc
@using Sitecore.Mvc.Presentation
@model ProjectX.Views.Renderings.CustomRenderingModel

<div>
  <p>FieldValue: @Model.FieldValue</p>
</div>

3. Create a rendering model in Sitecore and assign it the Model Type value.

4. Assign the model to the rendering

5. Finally, publish the model and rendering, and assign it to the presentation details of the item where you want to display the view.

That's it for today.

Until next post!