ASP.NET Core 2.0 MVC Tag Helpers

Problem

How to use Tag Helpers in ASP.NET Core MVC to simplify the creation of data entry forms.

Solution

In an empty project, update the Startup class to add the services and middleware for MVC.

Add a Controller with these action methods.

Add a _ViewImports.cshtml page in Views folder. Add a directive to import the tag helpers.

Add a model to use on the data entry screen.

Add a Razor page (Index.cshtml).

Discussion

Tag Helpers help generate HTML by attaching attributes to the existing HTML elements or by creating new elements. Although they look like HTML elements and attributes, Tag Helpers are processed by Razor (server-side).

I like to think of Tag Helpers as C# extensions methods, i.e., they allow us to attach some extra behavior to the existing classes.

The sample project shows the usage of various tag helpers that can help in creating data entry forms. I have outlined the key information about these below:

Form

  • Generates HTML form’s action attribute.
  • Generate a hidden verification token field used with [ValidateAntiForgeryToken] attribute on [HttpPost] action method.
  • Can specify asp-route-[param], however, it will be ignored if the route parameter exists in the form as well.
  • Can use asp-route for named routes.

Input & Text Area

  • Generates id and <strong>name.
  • Generate validation attributes.
  • Generate type attribute based on model’s property type and data annotations.

Label

  • Generate for
  • Picks the [Display] attribute on the Model property as label text.

Validation

  • <strong>asp-validation-for: generates validation message for single property on model.
  • asp-validation-summary: generates validation messages for a model and it’s properties. You could choose the option to suppress individual property messages.

Select

  • Generates select and option
  • Can be populated by List<SelectListItem>, received from the model or injected service.
  • Can be populated by specifying enum type, using GetEnumSelectList().
  • Multi-selection enabled if asp-for is IEnumerable.
  • Can add default option too, these will be combined with the ones from a data source.

Anchor

  • Can generate href based on controller, action and route parameters.
  • Can generate href based route name.
  • Can generate href based host and protocol.
  • asp-route-[param] transmitted as query string if [param] not part of the route.
    1. <a asp-controller="Home" asp-action="Echo" [email protected]>Echo!</a><br />  
    2.  <a asp-route="namedRoute" [email protected]>Call Named Route</a><br />  
    3.  <a asp-host="tahir-naushad.com" asp-protocol="http">Blog</a>  
Source Code

GitHub