14 Apr 2025

Udemy - .Net Core True Ultimate Guide

About


Notes from the following Udemy course




Chapter 17 - Tag Helpers


About Tag Helpers


What are tag helpers

  • classes that can be invoked as an html tag or an html attribute
  • processed at runtime on the server. When the razor view is compiled, asp.net core looks for html elements with special attributes like asp-for and asp-controller, they are parsed and transformed into the html output sent to the client

Example

  • <input aspfor="ModelProperty">
  • gets transformed into
  • <input type="text" name="ModelProperty" id="ModelProperty" value="ModelValue">

Predefined Tag helpers for <a> <form>

  • asp-controller
  • asp-action
  • asp-route-x
  • asp-route
  • asp-area

Predefined Tag helpers for <input> <textarea>, <label>

  • asp-for

Predefined Tag helpers for <select>

  • asp-for
  • asp-items



Importing Tag Helpers


How to import

  • In order to use the predefined tag helpers you must first import them
  • The following snippet of code is conventionally put in the _ViewImports.cshtml file in razor & MVC
  • The structure is @addTaghelper * {DLL_NAME}
  • @addTagHelper *, Microsoft.AspNetCore.MVC.TagHelpers



Form Tag Helpers


This is a regular anchor tag

<a href="~/persons/index" class="link-hover">Back to persons index page</a>

This is an anchor tag with the tag helpers asp-controller and asp-action

<a asp-controller="Persons" asp-action="Index" class="link-hover">Back to index page</a>




Input Tag Helpers


<input asp-for="ModelProperty />"

is equivalient to …

<input type="text" name="ModelProperty" id="ModelProperty" value="ModelValue" data-val-rule="ErrorMessage" />




Adding datatype to the Model


  public class PersonAddRequest{
    // HERE WE ARE ADDING THE DATATYPE THAT WILL BE USED IN THE RENDERING OF THE VIEW
    [DataType(DataType.Text)]
    public string? PersonName { get; set; }

    // HERE WE ARE ADDING THE DATATYPE THAT WILL BE USED IN THE RENDERING OF THE VIEW
    [DataType(DataType.EmailAddress)]
    [Required(ErrorMessage = "Email can't be blank")]
    public string? Email { get; set; }

    public Person ToPerson() {
      // ...
    }
  }





Tags:
0 comments