What is a View Component

Resolving view component view

View component is resolved in the same way razor views are resolved for controller actions - by convention

Creating ViewComponent

ViewComponent class: ViewComponents/SpeakerCardViewComponent.cs

using Microsoft.AspNetCore.Mvc;
using WebAppTagHelper.Models;

namespace WebAppTagHelper.ViewComponents
{
    public class SpeakerCardViewComponent : ViewComponent
    {
        public IViewComponentResult Invoke(Speaker speaker)
        {
            return View(speaker);
        }
    }
}

ViewComponent view: Views/Home/Components/SpeakerCard/Default.cshtml

@model WebAppTagHelper.Models.Speaker


<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3">
    <div class='card'>
        <div class='card-img'>
            <img src='static/speakers/Speaker-@(Model.SpeakerId).jpg' />
        </div>
        <h4 class='card-title'>
            <a href='#'>@(Model.UserFirstName) @(Model.UserLastName)</a>
        </h4>
        <p class='card-position'>@(Model.Company)</p>
        <p class='card-description'>Session time to be announced</p>
        <ul class='social'>
            <li>
                <a target='_blank' href='#'>LinkedIn</a>
            </li>
            <li>
                <a target='_blank' href='#'>Microsoft</a>
            </li>
        </ul>
    </div>
</div>

Invoking a view component

From view: Component.InvokeAsync(...)

<div class="container">
    <speaker-track track-name="JavaScript">
        @await Component.InvokeAsync("SpeakerCard", speakers[0])
        @await Component.InvokeAsync("SpeakerCard", speakers[1])
        @await Component.InvokeAsync("SpeakerCard", speakers[2])
    </speaker-track>
</div>

From view: tag helper syntax (must use prefix vc:)

<div class="container">
    <speaker-track track-name="JavaScript">
        <vc:speaker-card speaker=@speakers[0]></vc:speaker-card>
        <vc:speaker-card speaker=@speakers[1]></vc:speaker-card>
        <vc:speaker-card speaker=@speakers[2]></vc:speaker-card>
    </speaker-track>
</div>

From controller

public IActionResult IndexVC()
{
  return ViewComponent("PriorityList", new { maxPriority = 3, isDone = false });
}

Details: https://aspnetcore.readthedocs.io/en/stable/mvc/views/view-components.html#invoking-a-view-component