Sitecore MVC: View Rendering errors with GlassView

This is applicable to Glass Mapper 4.2, though it might be applicable in other versions with some tweaks (e.g. in version 3 you’ll need to create Models in Sitecore, as discussed on the Glass Mapper website). Another thing to note is that I’ve had some issues with Glass Mapper 4.3, as there were some big changes under the hood with that one.

When using a GlassView with a View Rendering (as opposed to a Controller Rendering) you will get an Exception when there is no Datasource set for the control. Out of the box, Exceptions in a single View are not handled nicely.

I’ve based my solution for this on a solution by Hedgehog, which gracefully outputs exception error messages in Experience Editor:

http://www.hhog.com/blog/robust-mvc-rendering-exception-handler/

I’ve basically just added an extra bit of handling for an empty Datasource. The error you will see in this scenario is:

The model item passed into the dictionary is of type ‘Sitecore.Mvc.Presentation.RenderingModel’, but this dictionary requires a model item of type XXXX

So my solution requires the following:

1) your templates should inherit from Sitecore.Mvc.Presentation.RenderingModel

I’ve got a base template for all of my templates called “BaseTemplate” that inherits from this.

2) Add these three classes to your solution:

Pipeline to validate the View:
https://gist.github.com/blacktambourine/3f29767f6b538c155c224403ac343920

Exception Handler:
https://gist.github.com/blacktambourine/16493f39690b9c312b390dd6e6f35c2d

Missing Datasource Handler:
https://gist.github.com/blacktambourine/08da2a67b722351a85a3d6dbfff7abc4


3) Rename the “z.Glass.Mapper.Sc.ViewRender.config.example” to “z.Glass.Mapper.Sc.ViewRender.config”; then edit this file and update the namespace and assembly for the GetViewRendererWithItemValidation

e.g. Diversus.Core.Sitecore.Pipeline.GetViewRendererWithItemValidation, Diversus.Core.Sitecore