Skip to content

07 - Tag Helpers

Tag Helpers

  • Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. 
  • There are many built-in Tag Helpers for common tasks - such as creating forms, links, loading assets and more - and even more available in public GitHub repositories and as NuGet packages.
  • Tag Helpers are authored in C#, and they target HTML elements based on element name, attribute name, or parent tag.
  • Tag helpers do not replace Html helpers – there is not a Tag helper for every Html helper

<form>

  • asp-action
  • asp-all-route-data
  • asp-antiforgery
  • asp-area
  • asp-controller
  • asp-fragment
  • asp-route
  • asp-route-<parameter name>
1
2
3
4
5
6
<form 
    asp-controller="Account" 
    asp-action="Login" 
    asp-route-returnurl="@ViewData["ReturnUrl"]" 
    method="post" 
    class="form-horizontal">

Transforms to

1
<form method="post" class="form-horizontal" action="/Account/Login">
  • asp-controller="<Controller Name>"
  • asp-action="<Action Name>"
    Forms target is constructed out of controller and action tag helpers
  • asp-route="<Route Name from routing table>"
    Forms target is constructed using routing table
  • asp-route-<parameter name>="<value>"
    Parameter name is added to forms target (as query string or route parameter)
  • asp-antiforgery="true/false"
    Generate anti-forgery token as hidden value to form. Usually controlled by [ValidateAntiForgeryToken] attribute in Controller
  • asp-all-route-data
    Give a dictionary for all route/target parameters
  • asp-area
    Use area in route/target (usually not needed to specify explicitly)
  • asp-fragment
    add # to route/target

<div>

Asp-validation-summary – display validation summary in this div
- All – property and model - ModelOnly – only model - None - none

<input>

  • Asp-action, Asp-all-route-data, Asp-area, Asp-controller, Asp-fragment, Asp-route
  • asp-for="<ModelExpression>"
    Generates id and name attributes – used later in model binding
    Sets the type attribute – based on model type and data annotations
    Sets up client side validation
    asp-for="property1" becomes in generated code m=>m.property1
  • asp-format="<format>"
    use to format value
    <input asp-for="SomeNumber" asp-format="{0:N4}"/>
  • Input tag helper does not handle collections and templates – use Html.XxxxxFor

Input type is based on .NET type

  • .NET type - Input Type
  • Bool - type="checkbox"
  • String - type="text"
  • DateTime - type="datetime"
  • Byte - type="number"
  • Int - type="number"
  • Single, Double - type="number"

Or use data annotations

  • [EmailAddress] - type=”email”
  • [Url] - type=”url”
  • [HiddenInput] - type=”hidden”
  • [Phone] - type=”tel”
  • [DataType(DataType.Password)] - type=”password”
  • [DataType(DataType.Date)] - type=”date”
  • [DataType(DataType.Time)] - type=”time”

<span>

asp-validation-for

Display validation error (if there is one for this model property) in this span

1
<span asp-validation-for="LastName" class="text-danger"></span>

<label>

asp-for
Generate label for this model property

1
<label asp-for="LastName" class="col-md-2 control-label"></label>
1
<label class="col-md-2 control-label" for="LastName">LastName</label>

<textarea>

  • asp-for="<ModelExpression>"
    Generate textarea input for this model property.
    Id, name, validation

<select>, option group <optgroup>

  • asp-for="<ModelExpression>"
    specifies the model property
  • Asp-items
    sepcifies option elements (List)
1
<select asp-for="Country" asp-items="Model.Countries"></select> 
  • You can generate option list from enums using Html helper
1
2
<select asp-for="EnumCountry" 
    asp-items="Html.GetEnumSelectList<CountryEnum>()">
  • The HTML <optgroup> element is generated when the view model contains one or more SelectListGroup objects.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public CountryViewModelGroup()
    {
        var NorthAmericaGroup = 
            new SelectListGroup { Name = "NA" };
        var EuropeGroup = 
            new SelectListGroup { Name = "EU" };

        Countries = new List<SelectListItem>{
            new SelectListItem{
                Value = "MEX",
                Text = "Mexico",
                Group = NorthAmericaGroup
            },
            new SelectListItem{
                Value = "FR",
                Text = "France",
                Group = EuropeGroup
            },
...

<select> multi-select

The Select Tag Helper will automatically generate the multiple = "multiple" attribute if the property specified in the asp-for attribute is an IEnumerable

1
2
3
4
5
6
7
8
9
public class CountryViewModelIEnumerable
    {
        public IEnumerable<string> CountryCodes { get; set; }

        public List<SelectListItem> Countries { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "MX", Text = "Mexico" },
            new SelectListItem { Value = "CA", Text = "Canada" },
...

Collections

1
2
3
4
5
public class ToDoItem
{
    public string Name { get; set; }
    public bool IsDone { get; set; }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@model List<ToDoItem>
@for (int i = 0; i < Model.Count; i++)
    {
        <tr>
            <td>
            <label asp-for="@Model[i].Name"></label>
        </td>
        <td>
            <input asp-for="@Model[i].IsDone" />
        </td>
        </tr>
    }

<a>

  • Asp-action, Asp-all-route-data, Asp-area, Asp-controller, Asp-fragment,
    Asp-route, Asp-route-<parameter name>
  • Asp-host
    Specify host to use in generated link (default is relative to current host)
  • Asp-protocol
    Specify protocol to use (default is current protocol)

<img>

asp-append-version="<true/false>"

Enable cache busting. Generates file version hash and appends it to source.

<script>

1
2
3
4
5
6
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
    asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
    asp-fallback-test="window.jQuery"
    crossorigin="anonymous"
    integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
</script>
  • Asp-append-version
  • Asp-fallback-src
    If asp-fallback-test is negative (no network) then fall back to this location
  • Asp-fallback-test
    Javascript functionality to test
  • Asp-fallback-src-exclude, Asp-fallback-src-include, Asp-src-exclude, Asp-src-include
    Comma separated list of sources to include or exclude
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<link rel="stylesheet" href="https://…/3.3.7/css/bootstrap.min.css"
asp-fallback-href="~/lib/css/bootstrap.min.css"
asp-fallback-test-class="sr-only"
asp-fallback-test-property="position" 
asp-fallback-test-value="absolute"/>

<link 
rel="stylesheet" 
href="~/css/site.min.css" 
asp-append-version="true"/>
  • Asp-append-version
  • Asp-fallback-href
  • Asp-fallback-href-exclude
  • Asp-fallback-href-include
  • Asp-fallback-test-class
  • Asp-fallback-test-property
  • Asp-fallback-test-value
  • Asp-href-exclude
  • Asp-href-include

<environment>

  • Names="comma_separated_list"
    asp.net core pre-defines following enviroments – Development, Staging, Production. Useful for branching in cshtml files
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<environment names="Development">
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/…/css/bootstrap.min.css"
        asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
        asp-fallback-test-class="sr-only" asp-fallback-test-property="position" 
        asp-fallback-test-value="absolute"/>
    <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true"/>
</environment>

Html helpers

  • Tag helpers are there in addition to Html helpers.
  • Some functionality is only possible with Html helpers.
  • Html helpers generate full html tags – harder to read cshtml files, designers cant modify easily
  • Four main categories of helpers
    • Output
    • Input
    • Form
    • Link


Output

  • DisplayFor
  • DisplayForModel
  • DisplayNameFor
  • DisplayNameForModel
  • DisplayTextFor
  • LabelFor
  • LabelForModel

Input

  • EditorFor
  • TextAreaFor
  • TextBoxFor
  • DropDownFor
  • EnumDropDownFor
  • ListBoxFor
  • RadioButtonFor
  • HiddenFor
  • CheckBoxFor
  • PasswordFor

Form

  • BeginForm
  • BeginRouteForm
  • EndForm
  • AntiForgeryToken
  • HiddenFor

Link

  • ActionLink
  • RouteLink

EditorFor

  • EditorFor(expression)
  • EditorFor(expression, additionalViewData)
  • EditorFor(expression, templateName)
  • EditorFor(expression, templateName, additionalViewData)
  • EditorFor(expression, templateName, htmlFieldName)
  • EditorFor(expression, templateName, htmlFieldName, additionalViewData)


Expression - lambda

Html helpers, example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<dt>
    @Html.DisplayNameFor(model => model.FirstName)
</dt>
<dd>
    @Html.DisplayFor(model => model.FirstName)
</dd>

...

@Html.EditorFor(
    model => model.Participant.FirstName, 
    new { htmlAttributes = new { @class = "form-control" } }
)

@Html.ValidationMessageFor(
    model => model.Participant.FirstName, 
    "", 
    new { @class = "text-danger" }
)

@Html.ActionLink("Show items", "Show", new { id = 1}, 
    htmlAttributes: new { @class = "btn btn-primary", role = "button" })