Tag Helpers In Asp.Net Core MVC

All about Tag helpers in asp.net core MVC explained by sagar jaybhay

Asp page tag helper / Tag helpers in Asp.net Core MVC

  • This is new in Asp.net core.
  • These are a server-side component.
  • It is processed on the server and renders an HTML element in razor files.
  • It is similar to Html helpers
  • There are so many tag helpers like generating the link, creating forms, etc,
  • To use tag helper we need to import these tag helper first.

For example, we need to create anchor a tag with the help of tag helper

<a asp-controller="home" asp-action="Details" asp-route-id="@stud.StudentId">Details</a>

In this

  • asp-controller= is took controller name
  • asp-action= is the action or method name present in that controller
  • asp-route-id= is the parameter we pass to that method.

You can see if we use Tag-Helper the color is changed syntax is good and clean. Now we can see the same example, by HTML helper.

@Html.ActionLink("Link Text","ActionName", "ControllerName", new { id = stud.StudentId });

Also, another way is to create an anchor element.

@Url.Action("details", "home", new { id = stud.StudentId });

The use of above method is that it returns string element.

Advantages of Tag Helper? / Why use Tag Helper?

Tag helper generates the link as per the route template. If in future you route template change these changes are present on startup.cs file and if you use regular Html static code or Html helper then newly generated URL is not present in that HTML file.

SagarJaybhay.com Tag Helper

Image Tag Helper:

Use general img tag but only in that add one asp-append-version=”true” property add so that it converts to image tag helper and it is very useful.

First, it enhances the <img> tag which provides cache-busting behavior for a static image file. First, understand what it means browser have cache functionality if we use image one and after the certain period we use image 2 but the name is same so the browser will show old file because when we use several times it saves in cache memory. To avoid this asp-append-version which enables us to append a unique hash value to the name of the image and it is calculated based on an image if our image change in future value will change.  So it means when our image on server change the new hash will be generated and it is appended to image.

<img class="card-img-top"  src="~/images/images.jpg" asp-append-version="true"/>
sagarjaybhay.com Image Tag Helper

Environment Tag Helper:

It used for conditionally loading or rendering the elements which are present inside the tag and it is based on hosting setting. Environment variables have a name attribute which we pass the comma-separated value which matches with hosting environment and result will produce.

<environment names="Staging,Production">
    <strong>HostingEnvironment.EnvironmentName is Staging or Production</strong>
</environment>

Include and Exclude attribute:
These include & exclude attributes which control the rendering of enclosed content based on the included or excluded hosting environment names.

<environment include="Staging,Production">
    <strong>HostingEnvironment.EnvironmentName is Staging or Production</strong>
</environment>

<environment exclude="Development">
    <strong>HostingEnvironment.EnvironmentName is not Development</strong>
</environment>

It is mainly used, to load minified or not minified means for development required CSS, js, jquery files like that.

Cache Tag Helper:

It is used to cache the content and improve the performance of asp.net application.

<cache>@DateTime.Now</cache>
The cache expiration time is 20 by default.
expires-on:- This attribute is used to set expiration date.
<cache expires-on="@new DateTime(2025,1,29,17,02,0)">
    Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>

expires-after:is used to set expires after the first request

<cache expires-after="@TimeSpan.FromSeconds(120)">
    Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>

Form Tag Helpers in Asp.Net Core:

To create strongly typed form in asp.net core we use form tag with adding asp-action,asp-controller like attribute so it becomes form tag helper.

To create strongly typed form use an asp-for attribute in your Html tag element like input, select, radio buttons. I am showing the example below in which Student is our model and it is strongly bound to our create form tag.

@model Student

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Student</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create" asp->
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="StudentId" class="control-label"></label>
                <input asp-for="StudentId" class="form-control" />
                <span asp-validation-for="StudentId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="FullName" class="control-label"></label>
                <input asp-for="FullName" class="form-control" />
                <span asp-validation-for="FullName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Address" class="control-label"></label>
                <input asp-for="Address" class="form-control" />
                <span asp-validation-for="Address" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Division" class="control-label"></label>
               <select asp-items="@Html.GetEnumSelectList<Divi>()"></select>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="List">Back to List</a>
</div>

In the above example, we also use a select tag. we have 3 ways to add data in a select tag but I am using only one way in which we take enum which declared enum in model.

 public enum Divi
    {
       A_8,
       B_8,
       A_9,
       B_9,
       A_10,
       B_10       
    }

So in asp-input, we use an asp-items attribute for which we use Html helper to enumerated list from that enum. Below is code for that

<select asp-items="@Html.GetEnumSelectList<Divi>()"></select>

Always remember the asp-action of form tag default point to the same method or action method which is called.

<form asp-action="Create" >

Asp.net tag list

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Related posts