Umbraco Partial Views with Razor

February 4, 2015
by Chris Sherman

Partial Views encapsulate a piece of your view for reuse throughout your site. Using them can remove cumbersome logic from your primary templates while keeping your code DRY. Let’s start with a basic use case for partial views: getting the most recent children of a node.

Right-click the Partials folder in Visual Studio (you may need to show all files and add this folder to your project) and add a new Razor view page named BlogLatestUpdates.cshtml. On this page I’ll inherit from UmbracoTemplatePage and proceed to select the five most recent children, displaying them in a group of div’s. I use a variation of this partial to render the “Latest updates” section next to my posts.

Now on your main template, reference the Partial View with the code below.

@Html.CachedPartial("BlogLatestUpdates", Model.Content, 86400000)

This helper references the Partial View I created, passes the IPublishedContent from the main template, and caches the response for one day. Note that this response will be cached across all pages. There are optional parameters you can supply for caching by page or by member.

Now suppose I want to create a Partial View and pass it specific data. In this case, I suggest adding a folder named ViewModels to your project and add a class to represent the data structure being passed. In this example, I’ll create a class named BlogItemTeaserViewModel to represent a blog post I want to render a sample of. The class looks like the following:

On my main template, I’ll render the Partial View with the following code, this time not caching the output. Each of the properties I assign to my view model object are defined on the document type of the node I’m passing it.

Since writing my first lines of code in elementary school I've developed expertise in software engineering, team leadership, and project management. Today I’m passionate about engineering fast, scalable applications powered by the cloud. My skills and experience enable me to deliver a holistic approach that generates results.