In today's post, you will learn about an alternative way of providing a typed safe architecture in your project, via UmbracoMapper. One of the aims of MVC is to be able to separate your presentation logic from your business logic. Being able to define document types with classes provides type-safety, allows us to use IntelliSense in our views and also makes our code testable.
Unfortunately, there is a few issue with using uSiteBuilder. For smaller sites, it works well but for larger projects, because uSitebuilder works by scanning all your assemblies on start-up, it can kill performance and make your sites start-up speed to take an age, making development very frustrating. Asides from that, not everyone may want to define document types via a class.
Creating A Property On The Document Type
Before we go into the auto mapping magic, let's set-up a property on a document type. I'm going to create one called 'MainTitle' On our page instance, I'm adding this text:
Installing UmbracoMapper is pretty painless. Open your Nuget package manager and type in 'UmbracoMapper'
How To Create A View Model With UmbracoModel
That's all the configuration you need. I'm going to assume you have a controller set-up for your document type. If you are unsure how to do this, then I recommend reading How To Add Your Own Controller and View Model In Umbraco first.
Creating A View Model
The first thing we need to do is create a view model for the document type. Umbraco provides us with a generic base content model for all the properties defined in IPublishedContent, this class is called 'PublishedContentModel'.
The first thing we need to do in the view model is to inherit from Umbraco.Core.Models.PublishedContent.PublishedContentModel and implement the constructor.
The next step is adding on any custom properties specific to your document type. As shown above, I added a property called 'MainTitle'. One thing to note from the screenshot above, is that the mapping takes places on the property alias. UmbracoMapper is case sensitive and the name in the alias needs to exactly match.
The next step is where the magic happens. First, we create a new instance of the UmbracoMapper. Next, we create a new instance of our view model and pass in the current page. UmbracoMapper copies all the properties from CurrentPage to the passed in object that shares the same property name.
The model has a property called MainTitle and it is set, the property will be copied into our NewsModel instance. No extra code is required, it just works.
When we run the code you can see 'MainTitle' is auto-populated in the view model with no code. Automapper in effect removes all the boring boiler plate code.