In my last post, What Is An Umbraco Macro I discussed the benefits and usages of macros. If you have worked on a bog-standard MVC site at all, you should be used to working with a partial view. Partial views are the MVC ways to create re-usable components within your project. In today's guide, I'm going to cover a simple pattern that will allow content editors to be able to drop MVC partials into the website.
Creating The View
The first thing we're going to do is create a simple partial view:
Creating The Macro
In our macro view (created in Views -> MacroPartials -> PartialViewMacroPicker.cshtml) we create a parameter called partial view, this parameter will be used to allow content editors to pass in the name of the partial they want to render. In the macro view, I've added a simple statement that checks the macro's parameter name, if it matches, it creates a new view model and passes that into the macro.
Create The Macro In Umbraco
In the Umbraco back-end, in the development section, create a new macro, add a parameter called 'partialView' and use the macro view 'PartialViewMacroPicker.cshtml' as the default render view. If you are unsure about how to do this, a more detailed guide can be found here.
Adding The Macro
If you go to a page that contains a text area, select the macro and set the 'partialView' parameter name to 'PartialViewExample', when the page gets rendered the macro view will be called, which in turn will render the MVC partial.
Displaying partial views within a page is simple to implement but can be a very powerful technique to allow custom layouts. Using this approach, a content editor can have a lot more power over how pages look, compared to the older days of creating very un-responsive and static pages.