In this tutorial, you will learn how to use normal .NET partial views within a Umbraco CMS powered website. If you have worked on a vanilla MVC site, it is highly likely that you will have encountered a partial view. A partial view is the ASP.NET Frameworks mechanism to allow developers to add re-usable components to web pages. In this guide, you will learn about a simple pattern that will allow content editors to be able to drop MVC partials into a web page from within the CMS. If you want to learn how to easily work with partials within Umbraco CMS, read on 🔥🔥🔥
Partial Views Within Umbraco
The first step is to create a simple partial view:
To create a partial, create a view with a .cshtml
extension here:
View
âž¡ Partials
Umbraco Macros
In order to give a content editor the ability to pick what partial view they want to have rendered on a page, we will need to create a Umbraco Macro. A macro is a reusable component that can be dropped into any rich-text property defined on any page. To learn more about macros in Umbraco read this tutorial. The code to create this macro is shown below:
To create a macro, you need to create a view with a cshtml
extension. In this example, the view is called PartialViewMacroPicker.cshtml
and it needs to be created here:
Views
âž¡ MacroPartials
This macro needs to be created with a single parameter. This parameter will be called partial view
. This parameter will be used to allow content editors to pass in the name of the partial view that they want to be rendered on the page. On-Line 6, I've added a simple statement that checks the parameters value against a partial view name. If it matches, to follow a good architecture, I create a view model and then call the partial view. This approach means you will always need to update this file every time you introduce a new partial view. The benefit of this approach is that the code in the partial view can follow a better paradigm.
Create The Macro In Umbraco
The final step is to enable the macro in the CMS. To do this, load the Umbraco backend. In the development
section, create a new macro. Add a parameter to this macro called partialView
. Finally, associate the default macro view, PartialViewMacroPicker.cshtml
💥
If you are unsure about how to do this, a more detailed guide can be found here 😊
With the macro defined, you can add it to a page. Create a new page, or find an existing page that contains a text area and within it, click on the macro icon. Select the new macro and set the partialView
parameter name to PartialViewExample
. The next time 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 and quick to implement, however, it can be a very powerful technique to allow custom layouts to be built within Umbraco. Using this approach, a content editor can have a lot more power over how a page is structured. Happy Coding 🤘