I have been following the guidance given in Katarina's blog post about using ViewModels in DD4T. However, in spite of the fact that she only uses @Html.Render(cp)
in her examples, I was tempted to use other helper methods. In this example you can see that I tried to use RenderComponentPresentationsByView()
@model DD4T.Indi.Models.GeneralPageViewModel
@{
ViewBag.Title = Model.Title;
}
<header class="header">
@Html.RenderComponentPresentationsByView("Hero Message CT")
</header>
<div id="main" class="main-content" role="main">
<div id="region-Main">
@foreach (var cp in Model.ComponentPresentations.Where(c => c.RenderData.View == "ContentBlock"))
{
@Html.Render(cp)
}
</div>
</div>
Having gone off-piste like this, I rapidly ended up in trouble, with NullReferenceExceptions coming from an 'unknown module'. On more detailed examination, I realised that the code I was executing was in DD4T.Mvc.Html.TridionHelper
, which is marked as [Obsolete("Consider changing to ViewModels and rendering them with the RenderHelper")]
. As my ViewModel class did not implement IPage, this broke the expectations of the framework code.
So - it's now clear to me that when using ViewModels, I can and should use @Html.Render(cp)
, and that using RenderComponentPresentationsByView()
is a bad idea - although presumably a good idea if you are using the old-skool approach.
I would like to know what strategy can I employ to determine which methods belong with which technique, and how I can avoid making similar mistakes (which are very time-consuming to analyse).
Further - what guidelines might represent good practice for this kind of work? For example, do people typically expose pre-filtered lists of component presentations from their model? I have succeeded in filtering in the razor view using a lambda expression, but what's the best way of doing this, and are there any known anti-patterns?