How To Allow Content Editors To Add Partials Into Umbraco

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 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:

@inherits Umbraco.Web.Mvc.UmbracoViewPage<JonDJones.BusinessLayer.ViewModel.PartialViewExample>
Hello

Creating The Macro

@inherits Umbraco.Web.Macros.PartialViewMacroPage
@{
var partialView = (string)Model.MacroParameters["partialView"];
if (partialView == "PartialViewExample")
{
var partialViewExample = new JonDJones.BusinessLayer.ViewModel.PartialViewExample();
@Html.Partial(partialView, partialViewExample)  
}
}

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.

Conclusion

In today’s tutorial, we’ve covered some very basic examples about how to add partial view rendering decisions to content editors. This principle is very simple but very powerful and can be built upon in many different ways. 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.

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *