ASP.NET Core Helpers

TagHelpers and HtmlHelpers

Helpers

When creating view templates with ASP.Net MVC Core we can use Razor syntax to achieve conditional rendering, looping, and rendering values from our model.

By using TagHelpers and HtmlHelpers we can add both client and server side input validation to our forms in a very DRY way. Additionally, we'll get intellisense and type checking to our model binding.


Examples

Tag Helper

<label class="caption" asp-for="FirstName"></label>

Html Helper

@Html.Label("FirstName", "First Name:", new {@class="caption"})

Output

<label class="caption" for="FirstName">First Name</label>

In addition to using less code, and less complex syntax, the TagHelper also benefits from better Intellisense support.


Form Tag Helpers

  • Generates the html form's action attribute value.
  • Adds fancy stuff to prevent XSRF attacks (requires [ValidateAntiForgeryToken] Action method)
  • Allows compile time errors if you mess up the Controller or Action names.
<form asp-controller="Demo" asp-action="Register" method="post">
  <!-- Input and Submit elements -->
</form>
<form method="post" action="/Demo/Register">
  <!-- Input and Submit elements -->
  <input
    name="__RequestVerificationToken"
    type="hidden"
    value="<removed for brevity>"
  />
</form>

Input Tag Helpers

  • Generates both id and name HTML attributes for you.
  • Sets the HTML type attribute automatically based on the model's property type. Input types generated include: number, text, checkbox, datetime.
  • Generates HTML5 validation attributes based on data annotations applied to the model.
  • Again, strong typing here allows for compile time errors. Rad.

Model:

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email Address")]
    public string Email { get; set; }
}

View:

<input asp-for="Email" />

Output:

<input
  type="email"
  data-val="true"
  data-val-email="The Email Address field is not a valid email address."
  data-val-required="The Email Address field is required."
  id="Email"
  name="Email"
  value=""
/>

Field Validation

When we use a Helper to create an input for a field, the asp-for TagHelper will ensure that the field is validated.


Common Data Annotations

Annotation Description
[Required] Required field.
[Display(Name = "Foo")] Sets field's name.
[StringLength(100)] Max length of string field.
[Range(0, 100)] Sets max and min value for a numeric field.
[CreditCard] Enforces credit card format.
[Compare] Validates two properties in a model match.
[EmailAddress] Enforces email format.
[Phone] Enforces telephone format.
[RegularExpression] Validates that the data matches the specified regular expression.
[Url] Validates the property has a URL format.

using System.ComponentModel.DataAnnotations;
namespace FormsTagHelper.ViewModels
{
    public class SimpleViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email Address")]
        public string Email { get; set; }
    }
}

To Generate or not to Generate?

Sometimes generating a view can save you some time. Use them as a starting point, but don't be afraid to dive in. It's just HTML with some special tags at the end of the day.


Resources

There are quite a few other asp- tags and DataAnnotations. Rather than trying to memorize them all, get comfortable using the following resources to research what you need to do:

Tag Helpers in forms in ASP.NET Core

Model validation in ASP.NET Core MVC


Lets Generate Some Examples

Create some models with different property types and DataAnnotations and use the View Generator to create some views and check them out.