skip to content

Tag Helpers & View Components

Built-in tag helpers such as asp-for, asp-action and environment, writing your own TagHelper, and view components as widgets with their own logic. Interviewers compare them to partial views.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

6

In an ASP.NET Core MVC view, what does asp-for generate on input, label and validation tag helpers, and how are tag helpers switched on?

level: juniorimportance: must knowfreq 66%

answer

  1. a directive in _ViewImports.cshtml
  2. Mvc.TagHelpers assembly, wildcard
  3. a ModelExpression, not a string
  4. name keeps dots, id swaps them
  5. int to number, bool to checkbox plus hidden

basics

~20 s

asp-for binds an element to a model property: an input gets name, id, type, value and data-val attributes, a label gets for and the display name, a validation span shows that field's error. @addTagHelper in _ViewImports.cshtml enables them.

solid answer

~40 s

Tag helpers are server-side classes Razor attaches to ordinary HTML elements; the MVC template enables the built-in ones with `@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers` in `Views/_ViewImports.cshtml`. `asp-for` is a `ModelExpression` over the view's `@model`, so `<input asp-for="Quantity" />` writes `name="Quantity"` (the key model binding reads back on POST), an `id` with dots and brackets turned into underscores, a `type` inferred from the property (`int` gives `number`, `bool` gives `checkbox` plus a hidden `false` input, `[EmailAddress]` gives `email`), the current `value` (the attempted value from `ModelState` first) and `data-val-*` attributes from validation metadata. `<label asp-for>` writes `for` and the `[Display]` name, `<span asp-validation-for>` renders that field's error, and `<div asp-validation-summary="ModelOnly">` lists model-level errors.

code

razor · 18 lines
razor
@model PlantOrderForm

<form asp-controller="Orders" asp-action="Place">
    <div asp-validation-summary="ModelOnly"></div>

    <label asp-for="CustomerName"></label>
    <input asp-for="CustomerName" />
    <span asp-validation-for="CustomerName"></span>

    <label asp-for="Quantity"></label>
    <input asp-for="Quantity" />   @* type="number" *@
    <span asp-validation-for="Quantity"></span>

    <select asp-for="PotSize" asp-items="Html.GetEnumSelectList<PotSize>()"></select>

    <input asp-for="GiftWrap" />   @* checkbox + hidden false *@
    <button type="submit">Order</button>
</form>

go deeper

for a junior

Recall the @addTagHelper line in _ViewImports.cshtml and what asp-for writes on an input: name, id, type, value and validation attributes.

for a middle

Explain that asp-for is a ModelExpression, how the name drives the POST binding, why the value comes from ModelState, and the checkbox hidden input.

for a senior

Diagnose forms that do not bind: foreach-generated names, a missing directive leaving asp-for in the HTML, and model changes hidden by stale ModelState values.

for a principal

Weigh tag helpers against HTML helpers and editor templates for a large form estate, keeping names consistent so binding and validation stay predictable.

## What a tag helper is A **tag helper** is a C# class that runs on the server while Razor renders a view. Razor matches it to an ordinary-looking HTML element or attribute, so `<input asp-for="Quantity" />` still reads like HTML but is processed by `InputTagHelper` before anything reaches the browser. Tag helpers are the markup-friendly counterpart of the older **HTML helpers** such as `@Html.TextBoxFor(m => m.Quantity)`; both call the same `IHtmlGenerator`, so the generated HTML matches. Tag helpers simply keep the view readable for anyone who knows HTML. ## Switching them on The built-in tag helpers live in the `Microsoft.AspNetCore.Mvc.TagHelpers` assembly, and a view uses only the tag helpers a directive has registered: ```razor @* Views/_ViewImports.cshtml *@ @using GardenCentre.Web.Models @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers ``` - The MVC and Razor Pages templates already put this line in `_ViewImports.cshtml`, which applies to every view in that folder and below. - `*` means every tag helper type in the assembly; your own tag helpers need a second line naming your project's assembly. - Without the directive, `asp-for` is an unknown attribute and is sent to the browser unchanged, a common cause of "my tag helper does nothing". ## What asp-for writes on an input `asp-for` is typed as a `ModelExpression`: Razor turns the attribute value into an expression over the view's `@model`, so `asp-for="Quantity"` means `Model.Quantity` and a misspelled property is a **compile error**. Take a garden-centre order form whose view model has `[Required] string CustomerName`, `[Range(1, 50)] int Quantity`, `[EmailAddress] string Email` and `bool GiftWrap`. The input tag helper fills in: 1. **`name`**: the expression path (`Quantity`, `Delivery.Postcode`, `Lines[0].Quantity`), exactly the key model binding reads on the POST. 2. **`id`**: the same path with dots and brackets replaced by underscores (`Delivery_Postcode`, `Lines_0__Quantity`), so a label can point at it. 3. **`type`**: inferred from the property unless you write `type` yourself (table below). 4. **`value`**: the attempted value from `ModelState` first, then the model. After a failed POST that returns `View(form)`, the user sees what they typed, even `abc` in a number field. 5. **`data-val-*`** attributes describing the validation attributes, while client validation is enabled (the default). What those rules do in the browser is a validation topic, not a tag helper one. | Property | Generated `type` | |---|---| | `string` | `text` | | `int`, `long` and other integers | `number` | | `decimal`, `double`, `float` | `text` | | `bool` | `checkbox`, plus a hidden `false` input | | `[EmailAddress]` | `email` | | `[DataType(DataType.Password)]` | `password` | | `DateTime` | `datetime-local` | | `IFormFile` | `file` | ## Labels, messages, the summary and selects - `<label asp-for="CustomerName">` writes `for="CustomerName"` and, when the label has no content, the `[Display(Name = ...)]` text or the property name. - `<span asp-validation-for="Quantity">` renders that property's server-side error and a `data-valmsg-for` hook for client scripts. - `<div asp-validation-summary="ModelOnly">` lists errors that are not tied to a property; `All` lists every error and `None` renders nothing. - `<select asp-for="PotSize" asp-items="Model.PotSizes">` writes `name` and `id`, builds `<option>` elements from an `IEnumerable<SelectListItem>` and selects the current value; a collection-typed property adds `multiple`. - `<textarea asp-for="Notes">` does the same for multi-line text. ## Two behaviours that trip people - **The checkbox.** An unchecked HTML checkbox posts nothing, so the input tag helper adds `<input name="GiftWrap" type="hidden" value="false">`, by default at the end of the form (`CheckBoxHiddenInputRenderMode.EndOfForm` on `HtmlHelperOptions`). Checked, the form posts `true` and then `false`, and binding to `bool` takes the first value. - **The loop.** The `name` comes from the expression text. Inside `@foreach (var line in Model.Lines)`, `asp-for="@line.Quantity"` produces `name="line.Quantity"`, which does not bind back to `Lines`. A `for` loop with `asp-for="Lines[i].Quantity"` produces `Lines[0].Quantity`, which does. In an interview, the strong answer names the registration directive, the five things the input helper writes, and why the name matters for the POST that follows.

  • Why does a bool property bound with asp-for render a hidden input as well as the checkbox?
    An unchecked checkbox sends nothing, so the property could never be bound back to `false`. The input tag helper adds a hidden `value="false"` input with the same name, by default at the end of the form (`CheckBoxHiddenInputRenderMode.EndOfForm`). Checked, the form posts `true` and `false`, and binding to `bool` takes the first value. `CheckBoxHiddenInputRenderMode.None` on `HtmlHelperOptions` turns the hidden input off.
  • Why does asp-for inside a foreach over Model.Lines break model binding on the POST?
    The generated `name` is the expression text. `asp-for="@line.Quantity"` on a `foreach` variable yields `name="line.Quantity"`, and the binder looking for `Lines[0].Quantity` finds nothing. Index into the collection with a `for` loop (`asp-for="Lines[i].Quantity"`) or render each line through an editor template so the names carry the `Lines[n]` prefix.
  • Where does the value attribute come from when a form is re-displayed after a failed POST?
    From `ModelState` first. The input tag helper asks the generator for the attempted value stored under the field's name, and only falls back to the model property when there is none. That is why a rejected `abc` in a number field is shown back to the user, and why changing the model in the POST action without clearing `ModelState` seems to have no effect.

  • asp-for takes a plain string, so a misspelled property only fails at runtime
  • Tag helpers work in any view without an @addTagHelper directive
  • The value attribute always shows the model property, even after a failed POST
  • asp-for on a decimal property renders type="number"
  • The generated id and name are always identical, dots included
open as a page

In ASP.NET Core MVC, when would you build a view component instead of a partial view, and how do you write and invoke one?

level: middleimportance: must knowfreq 55%

basics

~20 s

Use a view component when a reusable widget needs its own logic or data, such as a basket summary on every page; a partial view only renders the model its caller passes. A view component is a class with InvokeAsync and its own view.

open as a page

In ASP.NET Core MVC, how do the anchor and form tag helpers turn asp-controller, asp-action and asp-route-* attributes into a URL?

level: middleimportance: should knowfreq 46%

basics

~20 s

Both helpers pass asp-controller, asp-action, asp-area and each asp-route-{name} value to MVC's URL generation; a value matching a route parameter fills that segment, any other becomes a query-string pair, and an omitted controller or action reuses the current one.

open as a page

In an ASP.NET Core 10 MVC layout, what do the environment tag helper and asp-append-version do, and how does MapStaticAssets change asp-append-version?

level: middleimportance: should knowfreq 38%

basics

~20 s

The environment tag helper renders its content only when IWebHostEnvironment.EnvironmentName matches include and not exclude. asp-append-version busts caches: with MapStaticAssets it writes the fingerprinted asset URL, otherwise it appends ?v= and a hash of the file.

open as a page

In ASP.NET Core, how do you write a custom tag helper, and how do HtmlTargetElement, Process and TagHelperOutput decide what it renders?

level: seniorimportance: should knowfreq 34%

basics

~10 s

Derive from TagHelper, choose the element with [HtmlTargetElement] or the class-name convention, expose attributes as properties, and override Process or ProcessAsync to change TagHelperOutput: TagName, Attributes and Content. Then register the assembly with @addTagHelper.

open as a page

In an ASP.NET Core MVC view, how does the cache tag helper store a rendered fragment, how long by default, and what varies its entries?

level: seniorimportance: nice to knowfreq 21%

basics

~20 s

The cache tag helper renders its content once and keeps the HTML in a private in-memory cache on each server, for a 30-second sliding expiry unless told otherwise. vary-by-* attributes split entries by user, route, query, header, cookie or culture.

open as a page