Hej! Actually doing some Umbraco 13 work and wanted to sense check my use of View Components.
Example:
- Rootpage with multiple Tracks (listed as "Singles", because music init)
- Want to display details of each Track in a card
- Want to move the code for each of these cards into a dedicated component, passing the Track instance as an parameter
My general approach would be to make a View Component (
TrackCardViewComponent.cs
) which returns the code for the card, using input of
@model Track
. I've included the code at the end of this message.
This works just fine - I more or less want to confirm this is the correct approach, or if I'm over-complicating things. My crucial reason for using the View Component was to pass the Track instance as an parameter to the card, but that might be possible via other means.
All comments/advice/direction appreciated!
Rich
Rootpage.cshtml:
<div class="row row-cols-3 p-0 m-0">
@foreach (Track track in Model.Singles)
{
@await Component.InvokeAsync("TrackCard", track)
}
</div>
TrackCardViewComponent.cs:
public class TrackCardViewComponent : ViewComponent
{
public IViewComponentResult Invoke(Track track)
{
return View("~/Views/ViewComponents/TrackCard.cshtml", track);
}
}
TrackCard.cshtml:
@model Track
@if (Model.TrackArtwork is null) return;
<div class="col-sm-6 col-md-4 p-2">
<img class="w-100" src="@Model.TrackArtwork.MediaUrl()" />
<p>@Model.Name | @Model.TrackArtwork.MediaUrl()</p>
<p>Test</p>
</div>