Skip to content

9.5 — Partial Views, View Components, Tag Helpers vs HTML Helpers

← Roadmap · Section: 9. MVC, Razor Pages and Views Prev: 9.4 Razor and layouts · Next: 9.6 ViewData, ViewBag and TempData

Markers: ⭐ · Confidence: 🔴 · Last reviewed: —


TL;DR

Three ways to reuse markup, for three different situations.

  • Partial view — a fragment of Razor that renders whatever model you hand it. No logic, no data fetching.
  • View component — a small class plus a view, with its own dependencies and its own data. For a fragment that needs to load something.
  • Tag helpers — server-side attributes on HTML elements (asp-for, asp-action). The modern replacement for HTML helpers.

Definitions

Term What it is What it means
Partial view a .cshtml fragment Reusable markup rendered with a model passed in. No behaviour of its own.
<partial /> a tag helper The modern way to render a partial. Async by default.
Html.Partial / RenderPartial HTML helpers The older, synchronous forms. ⚠️ Can deadlock — see traps.
View component a class + a view A self-contained fragment with its own DI, logic and data access.
ViewComponent an abstract class The base class. Has an InvokeAsync method found by convention.
<vc:name /> a tag helper Invokes a view component from markup.
Tag helper a server-side attribute asp-for, asp-action. Processed on the server, renders plain HTML.
HTML helper a method @Html.TextBoxFor(...). The pre-Core approach. Still supported.
@addTagHelper a directive Registers tag helpers. Without it they render as literal attributes.
asp-for a tag helper attribute Binds an input to a model property — name, id, value and validation attributes.

The concept

Three tools, one question

The question that picks between them: where does the data come from?

Partial view — the caller supplies it.

<partial name="_OrderRow" model="line" />

The partial renders what it is given. It has no dependencies and asks for nothing.

View component — it fetches its own.

<vc:shopping-cart-summary user-id="@Model.UserId" />

The component has a class behind it that can inject services, query a database and decide what to render. A partial cannot do that without the @inject misuse from 9.4.

Tag helpers — they generate markup from the model.

<input asp-for="Email" class="form-control" />

That one attribute produces the name, id, type, current value and client-side validation attributes, all derived from the property.

A picture: a partial is a rubber stamp — same shape every time, ink supplied by you. A view component is a vending machine — it goes and gets the thing itself. Tag helpers are a typewriter's autocomplete — you write the intent and it fills in the mechanical detail.


How it works

The simple version — partial views

By convention, partials are named with a leading underscore:

@* Views/Shared/_OrderRow.cshtml *@
@model OrderLineViewModel

<tr>
    <td>@Model.ProductName</td>
    <td>@Model.Quantity</td>
    <td>@Model.LineTotal.ToString("C")</td>
</tr>
@* Rendering it *@
@foreach (var line in Model.Lines)
{
    <partial name="_OrderRow" model="line" />
}

⚠️ Use the <partial /> tag helper, not Html.Partial.

<partial name="_OrderRow" model="line" />      @* ✓ async, safe *@

@Html.Partial("_OrderRow", line)               @* ⚠️ synchronous — can deadlock *@
@{ Html.RenderPartial("_OrderRow", line); }    @* ⚠️ same *@

Html.Partial blocks on async work internally, which risks a deadlock and blocks a thread-pool thread (2.13). Visual Studio flags it with a warning for exactly that reason. <partial /> and @await Html.PartialAsync(...) are the safe forms.

⚠️ Partials cannot define layout sections. A partial containing @section Scripts { } silently does nothing, because sections belong to the view/layout relationship and a partial renders independently (9.4).

View components

Two pieces — a class and a view:

// ViewComponents/ShoppingCartSummaryViewComponent.cs
public class ShoppingCartSummaryViewComponent(ICartService carts) : ViewComponent
{
    // Found by convention, like middleware's InvokeAsync — see 5.5
    public async Task<IViewComponentResult> InvokeAsync(Guid userId)
    {
        var cart = await carts.GetAsync(userId, HttpContext.RequestAborted);

        return View(new CartSummaryViewModel
        {
            ItemCount = cart.Lines.Count,
            Total     = cart.Total
        });
    }
}
@* Views/Shared/Components/ShoppingCartSummary/Default.cshtml *@
@model CartSummaryViewModel

<a asp-controller="Cart" asp-action="Index" class="cart-summary">
    🛒 @Model.ItemCount items — @Model.Total.ToString("C")
</a>

⚠️ The view path is a strict convention and getting it wrong is the usual first-time failure:

Views/Shared/Components/{ComponentName}/{ViewName}.cshtml

{ComponentName} is the class name minus ViewComponent, and {ViewName} defaults to Default. So ShoppingCartSummaryViewComponent looks in Views/Shared/Components/ShoppingCartSummary/Default.cshtml.

Invoking it:

@* Tag helper form — needs @addTagHelper *, MyApp in _ViewImports *@
<vc:shopping-cart-summary user-id="@Model.UserId" />

@* Or the method form *@
@await Component.InvokeAsync("ShoppingCartSummary", new { userId = Model.UserId })

Note the kebab-case in the tag helper form — ShoppingCartSummary becomes shopping-cart-summary, and parameters follow the same conversion.

Partial versus view component

Partial view View component
Has a class ❌ ✅
Dependency injection ❌ ✅
Can fetch its own data ❌ ✅
Unit testable ❌ ✅
Can define layout sections ❌ ❌
Participates in routing ❌ ❌
Overhead Minimal Small

The deciding question stays the same: does the fragment need data the page did not already have? A cart summary in a layout does — every page shows it, and no controller wants to populate it. An order row does not — the page already loaded the order.

⚠️ A view component is not a controller. It has no route and cannot be requested directly, so it cannot serve an AJAX refresh. For that you need a real action returning PartialView(...).

Tag helpers versus HTML helpers

Both generate HTML from the model. Tag helpers look like HTML; HTML helpers look like C#.

@* Tag helper — reads as markup *@
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>

@* HTML helper — the older equivalent *@
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Email)

Tag helpers are preferred for three practical reasons:

They are valid HTML, so editors, formatters and designers handle them normally. An HTML helper is a C# method call that produces markup, which tooling cannot see into.

IntelliSense works on the attributes, including the model property names.

Attributes are natural. Compare class="form-control" with new { @class = "form-control" } — the @ prefix there is escaping a C# keyword, which is exactly the kind of friction tag helpers removed.

⚠️ Neither is deprecated. HTML helpers still work, and a few things — @Html.Raw, @Html.DisplayFor — have no direct tag helper equivalent. Mixed usage is normal in real codebases.

⚠️ What asp-for actually generates

<input asp-for="Email" class="form-control" />

renders as:

<input class="form-control"
       type="email"                              <!-- inferred from [EmailAddress] -->
       data-val="true"
       data-val-required="The Email field is required."
       data-val-email="Enter a valid email address."
       id="Email"
       name="Email"
       value="ada@example.com" />

One attribute produced seven. The name matters most — it must match the model property for model binding to work on POST (11.2), and asp-for guarantees it does.

The data-val-* attributes come from the validation attributes on the model (11.4) and drive client-side validation.

⚠️ Client-side validation is a convenience, not a control. It is trivially bypassed, so the server must validate too (11.8).

The common tag helpers

@* Forms — asp-action/controller generate the URL, and the form gets an antiforgery token *@
<form asp-controller="Orders" asp-action="Create" method="post">
    <input asp-for="CustomerName" />
    <select asp-for="CountryCode" asp-items="Model.Countries"></select>
    <button type="submit">Save</button>
</form>

@* Links — generated, not hard-coded. See 8.6. *@
<a asp-controller="Orders" asp-action="Details" asp-route-id="@order.Id">View</a>

@* Assets — asp-append-version adds a content hash for cache busting *@
<script src="~/js/site.js" asp-append-version="true"></script>

@* Environment-specific markup *@
<environment include="Development">
    <script src="~/js/debug.js"></script>
</environment>
<environment exclude="Development">
    <script src="https://cdn.example.com/app.min.js"></script>
</environment>

⚠️ A <form> with tag helpers gets an antiforgery token automatically. That is a genuinely useful default — it means the matching [ValidateAntiForgeryToken] on the action works without you adding a hidden field (17.4). Writing the form as plain HTML loses it.

The deeper detail — a custom tag helper

[HtmlTargetElement("status-badge", Attributes = "status")]
public class StatusBadgeTagHelper : TagHelper
{
    public OrderStatus Status { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "span";
        output.TagMode = TagMode.StartTagAndEndTag;

        var cssClass = Status switch
        {
            OrderStatus.Pending   => "badge bg-secondary",
            OrderStatus.Shipped   => "badge bg-success",
            OrderStatus.Cancelled => "badge bg-danger",
            _                     => "badge bg-light"
        };

        output.Attributes.SetAttribute("class", cssClass);
        output.Content.SetContent(Status.ToString());     // SetContent ENCODES — safe
    }
}
<status-badge status="@Model.Status" />

⚠️ SetContent HTML-encodes; SetHtmlContent does not. Using the second with anything user-supplied is an XSS hole (17.3).

Custom tag helpers suit repeated presentational logic — a badge, a currency display, a date format. Anything needing data belongs in a view component instead.


Code

A realistic combination:

@* Views/Shared/_Layout.cshtml — the cart needs its own data, so a view component *@
<header>
    <nav>
        <a asp-controller="Home" asp-action="Index">Home</a>
        <vc:shopping-cart-summary user-id="@User.GetUserId()" />
    </nav>
</header>
@* Views/Orders/Details.cshtml — rows use data the page already has, so a partial *@
@model OrderDetailsViewModel

<h1>Order @Model.Reference <status-badge status="@Model.Status" /></h1>

<table class="table">
    <tbody>
    @foreach (var line in Model.Lines)
    {
        <partial name="_OrderRow" model="line" />
    }
    </tbody>
</table>

@if (Model.CanCancel)
{
    @* Tag helpers generate the URL and add the antiforgery token *@
    <form asp-action="Cancel" asp-route-id="@Model.Id" method="post">
        <button type="submit" class="btn btn-danger">Cancel this order</button>
    </form>
}
@* Views/Orders/Edit.cshtml — a form using the full tag helper set *@
@model EditOrderViewModel

<form asp-action="Edit" method="post">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    <input type="hidden" asp-for="Id" />

    <div class="mb-3">
        <label asp-for="CustomerName" class="form-label"></label>
        <input asp-for="CustomerName" class="form-control" />
        <span asp-validation-for="CustomerName" class="text-danger"></span>
    </div>

    <div class="mb-3">
        <label asp-for="CountryCode" class="form-label"></label>
        <select asp-for="CountryCode" asp-items="Model.Countries" class="form-select">
            <option value="">-- Select a country --</option>
        </select>
        <span asp-validation-for="CountryCode" class="text-danger"></span>
    </div>

    <button type="submit" class="btn btn-primary">Save</button>
    <a asp-action="Details" asp-route-id="@Model.Id" class="btn btn-secondary">Cancel</a>
</form>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

Note the division: asp-for handles the mechanical detail — names, ids, values, validation attributes — while the model decides what the options are (Model.Countries) and what the rules are (its validation attributes). The view expresses layout, not logic.


Interview questions

Q: What is the difference between a partial view and a view component?

A partial view is just a fragment of Razor rendered with a model the caller supplies — it has no class, no dependency injection and cannot fetch anything. A view component is a class plus a view: it can inject services, query a database and decide what to render, so it suits a fragment that needs data the page did not already have. The deciding question is where the data comes from. A cart summary in a layout needs its own, since no controller wants to populate it on every page; an order row does not, because the page already loaded the order.

Q: Why prefer tag helpers over HTML helpers?

Three reasons. They are valid HTML, so editors, formatters and front-end tooling handle them normally, whereas an HTML helper is a C# method call that produces markup and tooling cannot see into. IntelliSense works on the attributes including model property names. And attributes read naturally — class="form-control" rather than an anonymous object with @class escaping a C# keyword. Neither is deprecated though, and a few things like Html.Raw have no tag helper equivalent, so mixed usage is normal.

Q: What does asp-for actually do?

It generates the mechanical attributes from the model property — name, id, value, an inferred type, and the data-val-* attributes that drive client-side validation, derived from the validation attributes on the model. The name is the important one, because it has to match the property for model binding to work when the form posts, and asp-for guarantees it does. One attribute typically produces six or seven.

Q: What is the risk with Html.Partial?

It is synchronous and blocks on async work internally, which risks a deadlock and pins a thread-pool thread. Visual Studio flags it with a warning for that reason. The <partial /> tag helper is async by default, and Html.PartialAsync is the awaited equivalent — either is the safe choice. It is worth knowing because Html.Partial still appears throughout older codebases and tutorials.


Traps ⚠️

  • Html.Partial and RenderPartial are synchronous and can deadlock. Use <partial />.
  • The view component path is a strict convention — Views/Shared/Components/{Name}/Default.cshtml. Wrong path means "view not found".
  • Partials and view components cannot define layout sections. The @section silently does nothing.
  • A view component is not a controller — no route, so it cannot serve AJAX. Use an action returning PartialView.
  • Missing @addTagHelper makes tag helpers render as literal attributes, with no error (9.4).
  • A custom tag helper needs its assembly registered with @addTagHelper *, MyApp.
  • SetHtmlContent does not encode. XSS risk with user data.
  • Plain HTML forms lose the automatic antiforgery token that tag helpers add.
  • Client-side validation is bypassable. The server must validate too.


Sources