How to add a macro to an MVC view in Umbraco.


You might have a control that you normally use as a macro in a page content field, but want to put that same macro directly into another control, such as a view. If you do, then here is a step by step guide for doing exactly that.

In my case, I had built a control to list news or products related to the page that the user was looking at. The control was designed to take an enum to determine what type of thing it should list, 'related news' or 'related products',

The problem was that I wanted to be able to use this same control in the footer control. I decided that the best way to achieve this would be to reuse the macro by referencing it in a view. 

This can be achieved by the following steps:

  1. Add @inherits Umbraco.Web.Mvc.UmbracoTemplatePage to your view
  2. Add the following, substituting the macro’s name, as named in Umbraco and you’re your own anonymous object defining any required arguments: @Umbraco.RenderMacro("RelatedArticles", new { ListType = RelatedItemsType.RelatedProducts })

You may encounter the error “The view must derive from WebViewPage, or WebViewPage<TModel>.”

This will be because you can either inherit from UmbracoTemplatePage or define a model, but not both. You can work around this by refactoring your view into a partial and reference it in another view that wraps it.

Bob Coppins Thumbnail
Bob Coppins
Senior Hosting & Application Support Engineer
Bob joined Sagittarius at the beginning of 2015, having worked as a service desk analyst for an internationally used software brand. He is an avid programmer and has written a number of software tools to support service desk operations and for personal use.
Bob Coppins Thumbnail

Bob Coppins

24 Aug 2016 - 4 minute read
share this

stay in the know, stay ahead.

Get the latest from the agency, including news, events and expert content.
explore services in the article
find out what we can do for you
read some of our case studies