Anchor, Link And Script Tag Helper In ASP.NET Core 3.1

Today in this blog we will discuss 3 tag helpers in ASP.Net Core: anchor tag helper, link tag helper, and script tag helper.

Here is the code.

Anchor tag helper

The anchor tag helper renders it as an HTML anchor tag. Anchor tag helper has attributes of asp-controller and asp-action and it also has the asp-route-id attribute to render id-based link or route. If the asp-action attribute value is Index, then no action is appended to the URL, leading to the invocation of the default Index action.

Link tag helper

The link tag helper renders as a link to the primary or fallback css file. The Link Tag Helper allows us to specify a CDN for the CSS file and a fallback when the CDN is not available. The Link Tag Helper provides the performance advantage of a CDN with the robustness of local hosting.

Script tag helper

The script tag helper renders as a link to the primary or fallback css file. The Script Tag Helper allows you to specify a CDN for the script file and a fallback when the CDN is not available. The Script Tag Helper provides the performance advantage of a CDN with the robustness of local hosting.

Step 1. Create an ASP.NET web application project in Visual Studio 2019.

Step 2. Create the class employee under the Models folder.

using System.ComponentModel.DataAnnotations;

namespace AnchorLinkScriptTagHelper_Demo.Models
{
    public class Employee
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [StringLength(100)]
        public string Name { get; set; }

        [Required]
        [StringLength(100)]
        public string Position { get; set; }

        [Required]
        [StringLength(100)]
        public string Office { get; set; }

        [Required]
        public int Salary { get; set; }
    }
}

Step 3. “Add” DbSet in ApplicationDbContext which is located under the data folder of your project.

using AnchorLinkScriptTagHelper_Demo.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace AnchorLinkScriptTagHelper_Demo.Data
{
    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<Employee> Employees { get; set; }
    }
}

Step 4. Now in the package manager console Add-migration InitialModel hit enter then update-database. It will add an employee table with all the properties.

Step 5. Open the same HomeController or a new controller and write the following code on the controller class.

using System.Linq;
using AnchorLinkScriptTagHelper_Demo.Data;
using Microsoft.AspNetCore.Mvc;

namespace AnchorLinkScriptTagHelper_Demo.Controllers
{
    public class HomeController : Controller
    {
        private readonly ApplicationDbContext dbContext;

        public HomeController(ApplicationDbContext context)
        {
            dbContext = context;
        }

        public IActionResult Index()
        {
            var employee = dbContext.Employees.ToList();
            return View(employee);
        }

        public IActionResult Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var employee = dbContext.Employees.FirstOrDefault(e => e.Id == id);
            if (employee == null)
            {
                return NotFound();
            }
            return View(employee);
        }
    }
}

Step 6. Now open the index view under the views folder and write the following code.

@model IEnumerable<AnchorLinkScriptTagHelper_Demo.Models.Employee>

@{
    ViewData["Title"] = "Home Page";
}

<p class="container py-4">
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>@Html.DisplayNameFor(m => m.Name)</th>
                <th>@Html.DisplayNameFor(m => m.Position)</th>
                <th>@Html.DisplayNameFor(m => m.Office)</th>
                <th>@Html.DisplayNameFor(m => m.Salary)</th>
                <th>Action(s)</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>@item.Name</td>
                    <td>@item.Position</td>
                    <td>@item.Office</td>
                    <td>@item.Salary</td>
                    <td>
                        <a asp-controller="Home" asp-action="Details" asp-route-id="@item.Id" class="btn btn-sm btn-primary rounded-0">Details</a>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</p>

Position

Step 7. Now “Add” details view click on the details action in the controller class. It will be added in the details view under the views folder as the default name.

@model AnchorLinkScriptTagHelper_Demo.Models.Employee

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

<p class="container py-4">
    <h4>Employee Details</h4>
    <hr />
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Name)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Position)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Position)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Office)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Office)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Salary)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Salary)
        </dd>
    </dl>
</p>
<p>
    <a asp-controller="Home" asp-action="Index" class="btn btn-sm btn-primary rounded-0">Back to List</a>
</p>

Employee Details

Link tag helper example

Now add the following code in _Layout for the Link tag helper.

Link tag helper has some attributes, properties, and methods.

  • href: This represents the linked resource. The address is passed through to the created HTML.
  • asp-fallback-href: The URL of a CSS stylesheet to fallback to in the case the primary URL fails.
  • asp-fallback-test-class: The class name defined in the stylesheet to use for the fallback test.
  • asp-fallback-test-property: The CSS property name to use for the fallback test.
  • asp-fallback-test-value: The CSS property value to use for the fallback test.
<link rel="stylesheet" 
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" 
      asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css" 
      asp-fallback-test-class="sr-only" 
      asp-fallback-test-property="position" 
      asp-fallback-test-value="absolute" 
      integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" 
      crossorigin="anonymous">

Script tag helper example

  • asp-fallback-test: The script method defined in the primary script to use for the fallback test.
  • asp-fallback-src: The URL of a Script tag to fallback to in the case the primary one fails.
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.4.1.min.js"
        asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
        asp-fallback-test="window.jQuery"
        crossorigin="anonymous"
        integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT">
</script>

Complete _Layout code for Link Tag helper and Script tag helper.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - AnchorLinkScriptTagHelper_Demo</title>
    <link rel="stylesheet" 
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" 
          asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css" 
          asp-fallback-test-class="sr-only" asp-fallback-test-property="position" 
          asp-fallback-test-value="absolute" 
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" 
          crossorigin="anonymous">
</head>
<body>
    <p class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </p>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.4.1.min.js" 
            asp-fallback-src="~/lib/jquery/dist/jquery.min.js" 
            asp-fallback-test="window.jQuery" 
            crossorigin="anonymous" 
            integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT">
    </script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @RenderSection("Scripts", required: false)
</body>
</html>

Summary

In this article, we have discussed anchor tag helper, link tag helper, and script tag helper. I hope you have understood the use of these 3 tag helpers.