In this tutorial, you will learn how to optimally work with MVC partials when using Umbraco CMS. Partials are handy when you want to render re-usable components on your site. Through partial views, you can split your page functionality up in order to provide greater re-use. When it comes to using partials in Umbraco, the CMS has a few tricks up its sleeve, if you want to know what they are read on 🔥🔥🔥

The Partial

In this guide, we will be creating a partial view that renders a websites primary navigation. The benefit of adding the menu HTML into a part is that it will avoid duplicating the HTML on every layout within your siteThe first thing we need to do is create a new MVC razor view called Menu.cshtml or something similar. Partial views should be created within this folder:

ViewsPartials

The code to create this menu partial is shown below:

As you can see a partial view is nothing special. The only important thing to note is that on Line 1, the import statement inherits from IPublishedContent rather than UmbracoTemplatePage. You only use UmbracoTemplatePage in pages or layouts. In a partial view, you can use any model you want. In order to render a partial, within a layout or page view, you can use this code:

The partial view above contains a code smell. The partial contains business logic. It contains the code to get the menu items based on the object passed in. Adding code inside of a view breaks the MVC paradigm, let us fix that. Let us say we now want to change the menu so it displays the menu items from the top-level pages. In order to improve our code, we will need to introduce a view model and inject it into the view. The view model will take in a list of pages in the constructor and contain all the code to get the menu items, like so:

The next step is to update the partial view work with HeaderViewModel instead of IPublishedContent:

Finally, we need to pass the view model from the page view/master layout into the partial:

In the snippet above, we pass in the list of child pages via the constructor. The view model exposes these menu items via a custom property called MenuItems. In the partial, set the inheriting type as HeaderViewModel. In our partial, we can then access that property by calling @Model.MenuItems 😊

Getting The HomePage

The last fix we should make is to change the menu items so they are returned from the home page rather than the current page. In Umbraco CMS, if you want to access the homepage in code, you can do this:

To access the homepage we should update our calling code like this:

In production, I recommend that you add this code into a controller and pass it down into the page view. To make this tutorial, as easy for you to follow I'm adding this code into the view 🤔


You are now a Umbraco partial view ninja 🐱‍👤. When building any site, you should make use of partial views whenever you can. Happy Coding 🤘