Umbraco

While working with Umbraco 9 I came across an issue where the razor view wouldn't accept my newly created view model. When loaded the page threw the below exception:

"ModelBindingException: Cannot bind source type DanMcilroy.Core.ViewModels.BlogViewModel to model type Umbraco.Cms.Core.Models.PublishedContent.IPublishedContent".

Exception:
ModelBindingException: Cannot bind source type DanMcilroy.Core.ViewModels.BlogViewModel to model type Umbraco.Cms.Core.Models.PublishedContent.IPublishedContent

From the exception it is telling us that the razor View was expecting a Model type of IPublishedContent. In order to fix this I had to make a few amendments in the Controller and ViewModel classes.

BlogViewModel:
BlogViewModel

In the BlogViewModel I inherited from the generated ModelBuilder class Blog, which is of type IPublishedContent, and implemented the base constructor. This will then give us the Blog data properties to use in the razor View.

BlogController:
BlogController

Finally we need to update the BlogController to new up the BlogViewModel and pass in the required parameters of CurrentPage and _publishedValueFallback.

Blog Razor View:
Blog Razor View

We have now successfully resolved the error, have the freedom of using both the Blog page data properties and further extending the ViewModel to included other properties.