• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Saturday, September 5, 2020

Tag Helpers in ASP.NET Core MVC

 Admin     September 05, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss Tag Helpers in ASP.NET Core MVC Application with some examples. Tag helpers are one of the new features introduced in ASP.NET Core MVC. Please read our previous article, where we discussed how to use bootstrap in ASP.NET Core MVC Application. As part of this article, we are going to discuss the following pointers.
  1. What are Tag Helpers in ASP.NET Core?
  2. Types of Tag Helpers
  3. How to use built-in Tag Helpers in ASP.NET Core MVC?
  4. Understanding the Anchor Tag Helper in ASP.NET Core
  5. Advantage of using Tag helpers in ASP.NET Core MVC Application
What are Tag Helpers in ASP.NET Core?
Tag Helpers in ASP.NET Core are the server-side components. They are basically used to perform defined transformations on HTML Elements. As they are server-side components, so they are going to be processed on the server to create and render HTML elements in the Razor files.

If you are coming from an ASP.NET MVC background, then you may be worked with the HTML helpers. The Tag Helpers are similar to the HTML helpers.

Types of Tag Helpers in ASP.NET Core:
There are two types of Tag helpers in ASP.NET Core. They are as follows:
  1. Built-In Tag Helpers: They come in-built in the ASP.NET Core Framework and can perform common tasks like generating links, creating forms, loading assets, showing validation messages, etc.
  2. Custom Tag Helper: That can be created by us to perform our desired transformation on an HTML element.
Note: In this article, I am going to discuss the Built-in Tag Helpers and in our upcoming articles, I will discuss the Custom Tag Helpers.

Please read the following articles before proceeding to this article as we are going to use layout, ViewImport, and bootstrap in this demo.

How to create and use Layout in ASP.NET Core?
Understanding the need and use of _ViewImport.cshtml file.
How to install bootstrap in ASP.NET Core?
Using Bootstrap in ASP.NET Core.


How to use built-in Tag Helpers in ASP.NET Core MVC?
In order to make the built-in tag helpers available for all the views of our application, import the tag helpers using the _ViewImports.cshtml file. You need to import them using the @addTagHelper directive as shown below.

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

The @addTagHelper makes the built-in tag helpers to available in the application which are defined in an assembly called Microsoft.AspNetCore.Mvc.TagHelpers. Here the wildcard “*” specifies that all the Tag Helpers are made available.

Generating Links using Tag Helpers in ASP.NET Core MVC Application:
Let us understand this with an example. First, create a class file with the name Student.cs within the Models folder. Once you create the Student.cs class file, then copy and paste the following code in it.
namespace FirstCoreMVCApplication.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string Branch { get; set; }
        public string Section { get; set; }
        public string Gender { get; set; }
    }
}
Modifying Home Controller:
Modify the Home Controller as shown below. Here we have created two action methods. To make the things simple and to keep the focus on Tag helpers, here we have hardcode the required student data within the action method.
using FirstCoreMVCApplication.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            List<Student> listStudents = new List<Student>()
            {
               new Student() { StudentId = 101, Name = "James", Branch = "CSE", Section = "A", Gender = "Male" },
               new Student() { StudentId = 102, Name = "Smith", Branch = "ETC", Section = "B", Gender = "Male" },
               new Student() { StudentId = 103, Name = "David", Branch = "CSE", Section = "A", Gender = "Male" },
               new Student() { StudentId = 104, Name = "Sara", Branch = "CSE", Section = "A", Gender = "Female" },
               new Student() { StudentId = 105, Name = "Pam", Branch = "ETC", Section = "B", Gender = "Female" }
            };
            return View(listStudents);
        }
        public ViewResult Details(int Id)
        {
            var studentDetails = new Student() { StudentId = Id, Name = "James", Branch = "CSE", Section = "A", Gender = "Male" };
            return View(studentDetails);
        }
    }
}
Creating the Details view:
Details.cshtml:
@model FirstCoreMVCApplication.Models.Student
@{
    ViewBag.Title = "Student Details";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row justify-content-center m-3">
    <div class="col-sm-8">
        <div class="card">
            <div class="card-header text-center">
                <h1>@Model.Name</h1>
            </div>
            <div class="card-body text-center">
                <h4>Studnet ID : @Model.StudentId</h4>
                <h4>Branch : @Model.Branch</h4>
                <h4>Section : @Model.Section</h4>
                <h4>Gender : @Model.Gender</h4>
            </div>
            <div class="card-footer text-center">
                <a href="#" class="btn btn-primary">Back</a>
            </div>
        </div>
    </div>
</div>
Index View: Now in the index view, we have to provide the View button as a link and on the click, on the View button, we need to display the Student Details. For example, we need to generate the following hyperlink. The number 101 is the ID of the student whose details we want to view.

/home/details/101

We have many different options to generate a link in ASP.NET Core MVC Application. Let us discuss all the possible options to generate a link and then we will discuss why we should use Tag Helper over others.

Option1: Manually generating the links:
@model List<FirstCoreMVCApplication.Models.Student>
@{
    ViewBag.Title = "Student List";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="table-responsive">
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>View</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var student in Model)
            {
                <tr>
                    <td>@student.StudentId</td>
                    <td>@student.Name</td>
                    <td class="text-center">View</td>
                </tr>
            }
        </tbody>
    </table>
</div>
Option2: Using HTML helpers
Tag Helpers in ASP.NET Core MVC

Option3: Using Tag Helpers:
In order to use Tag Helpers first import the @addTagHelper directive in the _ViewImport.cshtml file. Along with the @addTagHelper directive, we also add the model namespace using the @using directive. So, modify the _ViewImport.cshtml file as shown below which you can find within the Views folder.
@using FirstCoreMVCApplication.Models;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Then modify the Index view as shown below.
@model List<Student>
@{
    ViewBag.Title = "Student List";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="table-responsive">
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>View</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var student in Model)
            {
                <tr>
                    <td>@student.StudentId</td>
                    <td>@student.Name</td>
                    <td>
                        <a asp-controller="Home" asp-action="Details"
                           asp-route-id="@student.StudentId">View</a>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>
Now run the application and it should work as expected.

Understanding the Anchor Tag Helper in ASP.NET Core:
The Anchor Tag Helper in ASP.NET Core creates the standard HTML anchor (<a … ></a>) tag by adding new attributes such as:
  1. asp-controller: It is used to specify the controller to target based on the routing system. If you omitted this, then the controller of the current view is used by default.
  2. asp-action: It is used to specify the Action method to target based on the routing system. If you omitted this attribute then the action rendering the current view is used by default.
  3. asp-route-{value}: It is used for specifying the additional segment value for the URL. For example, asp-route-id is used to provide value for the ‘id’ segment.
The rendered anchor element’s “href” attribute value is determined by the values of these “asp-“ attributes. As the name says, the asp-controller specifies the name of the controller whereas asp-action specifies the name of the action name. Similarly, the asp-route-{value} attribute is used to include route data in the generated href attribute value. {value} can be replaced with route parameters such as id, name, etc.

Let us have a look at the following image.
Understanding the Anchor Tag Helper in ASP.NET Core MVC

As you can see in the above image, manually generating the links is much easier than using HTML Helpers or Tag Helpers. Then why should we use HTML helpers or Tag Helpers over manually generating these links in ASP.NET Core?

Advantage of using Tag helpers in ASP.NET Core MVC Application:
In ASP.NET Core MVC, the Tag Helpers generates links based on the application routing templates. That means. in the future, if we change routing templates, then the link generated by tag helpers will automatically reflect those changes made to the routing templates. So, the generated links just work as expected without any trouble.

On the other hand, if we have hard-coded the URL paths manually, then we need to change the code wherever we have hardcoded the path in our application when the application routing templates change.

Let’s understand this with an example
The following is the Startup class of our application. Please modify the Startup class as shown below.
Tag Helpers in ASP.NET Core MVC Application with Examples

As you can see in the above image, we have the route template pattern as {controller=Home}/{action=Index}/{id?}.

Generating Link Manually:
In the following code, we are manually generating the link by hard-coding the URL paths as /Home/Details.
View
Generating Link using Tag Helper:
In the following code, we are generating the link using an anchor tag helper.
View
As you can see with Tag Helper, we have not hardcoded the URL paths. Here, we are only specifying the controller and action names and the route parameters along with their values. When the tag helpers are executed on the server they look at the route templates and generate the correct URLs automatically.

Here, in both the techniques generate the same URL path i.e. (/Home/Details/101) and it also works with the current route template i.e. ({controller=Home}/{action=Index}/{id?})

Now let us change the routing template as shown below. Notice here in the route template, we have added the string literal “dotnet”.
Tag Helpers in ASP.NET Core MVC Application

With the above changes in place, now if you generate the link manually, then it will not work whereas if you generate the link with Tag Helpers then it will work as expected.

We also have tag helpers in ASP.NET Core to generate forms. When the form is posted back to the server, the posted form values are automatically handled and the associated validation messages are displayed. Without these tag helpers, we would have to write a lot of custom code to achieve the same. If this is not clear at the moment then don’t worry we will discuss this with examples in our upcoming articles.

That’s it for today. In the next article, I am going to discuss the Image Tag Helper in ASP.NET Core MVC Application. Here, in this article, I try to explain the basics of Tag Helpers in ASP.NET Core MVC Application with some examples. I hope you enjoy this article.

Summary:
I hope this post will be helpful to understand the concept of Tag Helpers in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape