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 Startup class to add services and middleware for MVC:

Add a controller with these action methods:

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

Add a model to use in data entry screen:

Add a razor page (Index.cshtml):

Discussion

Tag Helpers help generate HTML by attaching attributes to 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 extra behaviour to existing classes.

The sample project shows the usage of various tag helpers that can help in creating data entry forms. I’ll outline 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 exist 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 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 model and it’s properties. You could choose option to suppress individual property messages.

Select

  • Generates select and option
  • Can be populated by List<SelectListItem>, received from 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 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.

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Mvc.TagHelpers

Leave a Reply