One of the most useful novelties in DD4T 2.0 are the ViewModels. A ViewModel is a simple class, normally consisting only of properties, which is handed over to a view for rendering.
In this small series – published daily until Christmas – I will explain what view models are, how you create them and how you can use them.
What are ViewModels?
In previous versions of DD4T, the models were generic: either a Page or a ComponentPresentation. As a result, a developer who wanted to write views needed to have quite a bit of knowledge of Tridion, and especially of the specific implementation of Tridion he or she happened to be working on.
An example says more than a lengthy sentence, so look at the following Razor code:
<img src="@Model.Component.Fields["image"].LinkedComponentValues.Multimedia.Url" width="@Model.Component.Fields["image"].LinkedComponentValues.Multimedia.Width" height="@Model.Component.Fields["image"].LinkedComponentValues.Multimedia.Height" alt="@Model.Component.Fields["image"].LinkedComponentValues.MetadataFields["alt"].Value" />
This is a fairly typical way to write out an image. It may result in the following HTML:
<img src="/images/myimg_tcm4-132.png" width="400" height="200" alt="My image" />
The problem is not that you have to do a lot of typing to generate this simple ‘img’ element. The real issue is the amount of Tridion knowledge you need to pull this off. To an average .NET developer, this looks like complete abacadabra.
The idea of DD4T has always been to make it easier to build web sites based on SDL Tridion. So it was clear that something needed to be done. That is why we introduced view models in DD4T 2.0.
The idea is simple: create a specific model class for the different types of content you manage in Tridion, and hand that over to the views instead of the more generic types that you had to use in DD4T 1.
In their simplest form, ViewModels mirror the schemas in Tridion. The fields in the schema become properties in the ViewModel. This type of model can also be referred to as domain model.
Using a ViewModel, the same img element shown above can now be generated using this Razor code:
<img src="@Model.Image.Url" width="@Model.Image.Width" height="@Model.Image.Height" alt="@Model.AltText" />
A lot easier to read, and more importantly, easy to learn for any developer.
In the next article, I will explain how you can create a ViewModel class yourself.