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?
answer
- a directive in _ViewImports.cshtml
- Mvc.TagHelpers assembly, wildcard
- a ModelExpression, not a string
- name keeps dots, id swaps them
- int to number, bool to checkbox plus hidden
basics
~20 sasp-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 sTag 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@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
Recall the @addTagHelper line in _ViewImports.cshtml and what asp-for writes on an input: name, id, type, value and validation attributes.
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.
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.
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