Skip to content

How to use View Partials in Umbraco

Published: at 10:27 PM (2 min read)

My guide to how to share HTML markup where the params are coming from the same Model.

Table of contents

Open Table of contents

Background

I have not used Umbraco in a long time and I do not have many notes from when I did, so I am making some small things in it and writing these posts to document my understanding.

In this post we are going to look at how I have rendered the same markup when there is a shared Model. The use case I have is that most pages should be shown in there parent as cards (like blog posts in a blog collection).

Prerequisites

For this demo I have an Umbraco 13 app scaffolded out using the templates and the dotnet CLI.

The Composition

I have created a composition of settings called Card, that has an Image, Title, Subtitle and Excerpt. This is then shared with many of the page level document types to capture the details to be shown in the card view. The published Model is called PageMetadata and I will be using the interface to cast the IPublishedContent.

The View

Under the Views directory I have creates a dir called Partials and then one called Elements. In here I am storing all my Views that are going to be manually called by the developer to render the element.

The view will inherit from UmbracoViewPage and the generic type will be our IPageMetadata interface.

@inherits UmbracoViewPage<IPageMetadata>

<div class="card" style="width: 18rem;">
  <img src="@Model.CardImage.GetCropUrl("card")" class="card-img-top" alt="@Model.CardImage.Content.AltText">
  <div class="card-body">
    <h5 class="card-title">@Model.CardTitle</h5>
    <h6 class="card-subtitle">@Model.CardSubTitle</h6>
    <p class="card-text">@Model.Excerpt</p>
  </div>
</div>

Using it

To now use this on a page, we can call

@await Html.PartialAsync("~/Views/Partials/Elements/Card.cshtml")

Advanced: Passing Params

In another one of my posts I have spoken about using ViewComponents as they can be typed better than ViewPartials. IF you did need to pass some props in, you can update the block from Using it to

@await Html.PartialAsync("~/Views/Partials/Elements/Card.cshtml", new ViewDataDictionary(this.ViewData) {{"KEY", "VALUE"}})

This can then be accessed in the partial with the Model.Value("KEY") syntax.