This little featurette stemmed from a blog post on here looking at Getting a Sitecore Model from the cshtml. It’s something I think benefits us with Glass more than with regular Sitecore development.
Consider a .cshtml something like this (or using an @inherits Glass.Mapper.Sc.Web.Mvc.GlassView):
@using CardinalIT.Web @using Sitecore.Mvc @model CardinalIT.Model.Web.Common.INavigation <nav> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="index.html">@Model.Title</a> </div> @Html.Sitecore().Rendering(Constants.RenderingIds.Navigation.MainNavigation) </div> </nav>
Traditional Sitecore MVC
Traditional Sitecore MVC development would dictate that if we want to render this model, we could do in 1 of 2 realistic ways. Controller renderings – which are the slowest in my testing or View Renderings – which offer the ability to use them with dynamic presentation but don’t have a way of specifying model construction logic.
The vast majority of renderings in Sitecore have no real logic behind them, so I tend to favour View Renderings for their speed of implementation.
For view renderings you have to specify a model in Sitecore something like this:
Sitecore MVC with Glass V3
In Glass you are still left with the controller vs view rendering argument, but Glass’ model handling is subtley different. Glass (since V3) has always had an entry in the mvc.getModel pipeline that allows the model to be returned from Glass. This is pretty neat, but it still requires that you tell Sitecore what your model is.
Its worth noting at this time that using V3 – if you add the fully qualified type name of the model (instead of a link to a model in Sitecore) and ignore the messages when saving, Glass will actually pick up the model through its own GetModel pipeline entry.
Sitecore MVC with Glass V4
The above scenarios (as with the original Sitecore version) frustrates me for so many reasons. Firstly you will have to link the model to the rendering item which is just annoying, but more often around refactoring – try changing namespaces and see where you end up. I took the basis of a blog post from John West and since the cshtml always knows what model it is expecting, used it to allow Glass Mapper to determine the model. It is worth noting that Glass will attempt to find a declared model on the item first.
Now your rendering item declaration will simply look like this:
NICE, QUICK & SIMPLE 😀