Article

Tag Helpers in ASP.Net Core MVC

In this blog, we will learn Tag Helpers in ASP.Net Core MVC.

In this article, you will learn Tag Helpers in ASP.Net Core MVC.
Tag helpers are new features in ASP.NET Core MVC. First, understand about what are Tag Helpers and their use with an example.

Tag Helpers
Tag Helpers are generally server-side components. They are run on the server to create and render HTML elements in Razor files. Tag Helpers are much similar to HTML helpers. There are many built-in Tag Helpers for some tasks like generating links, creating forms, etc.

How to Importing Tag Helpers

To make the built-in tag helpers available for all the views in our entire application, import the tag helpers using _ViewImports.cshtml file. If you want to import tag helpers we use @addTagHelper directive.
ViewImports.cshtml File

@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers

Notes:
The wildcard (*) symbol indicates that here we want to import all the tag helpers Microsoft.AspNetCore.Mvc.TagHelpers is the assembly that contains the built-in tag helpers.

How to Generate Links using Tag Helpers
There are several ways we could do this in a razor view
1 : Manually Generating Links
home: Here Home is the controller name.
detailsemployee : Pass your Action name

    <a href="/home/detailsemployee/@employee.Id">View</a>

2:Using HTML helpers

@Html.ActionLink("View", "detailsemployee", new { id = employee.Id })

3: Using Tag Helpers

<a asp-controller="home" asp-action="details"
    asp-route-id="@employee.Id">View</a>

Anchor Tag Helper

The Anchor Tag Helper mainly role to enhance the standard HTML anchor () tag by adding new attributes such as
asp-controller: asp-controller specifies the controller name
asp-action: specifies the action name
asp-route-{value} :asp-route-{value} attribute is basically used to include route data in the generated href attribute value. {value} can be replaced with the route parameters such as id for example.

After running the page this link will be generate :

<a href="/Home/details/5">View</a>

Example for Tag Helpers in ASP.Net Core MVC
In this example, you can see when you will click the view button in front of you show specific employee details and click on the back button to go to the “http://localhost:25622/home/index”.
Add Employee.cs, MockEmployeeRepository.cs, IEmployeeRepository.cs and Dept.cs class in Model Folder
Employee.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace EmplloyeeManagement.Models
{
    public class Employee
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        [Required(ErrorMessage = "Provide Value for Email")]
        public string Email { get; set; }
        [Required]
        public Dept Department { get; set; }

    }
}

IEmployeeRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EmplloyeeManagement.Models
{
    public interface IEmployeeRepostory
    {
        Employee GetEmployee(int Id);
        IEnumerable<Employee> GetAllEmployees();
        Employee Add(Employee employee);
    }
}

MockEmployeeRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EmplloyeeManagement.Models
{
    public class MockEmployeeRepository : IEmployeeRepostory
    {
        private List<Employee> _employeList;
        public MockEmployeeRepository()
        {
            _employeList = new List<Employee>()
            {
                new Employee(){Id=1,Name="Laxmiant",Email="laxmikant.vnks@gmail.com",Department=Dept.Developer},
                new Employee(){Id=2,Name="Kishan",Email="Kishan.vnks@gmail.com",Department=Dept.HR },
                new Employee(){Id=3,Name="Mahesh",Email="Mahesh.vnks@gmail.com",Department=Dept.Networking },
                new Employee(){Id=4,Name="Karuna",Email="karuna.vnks@gmail.com",Department=Dept.HR }
            };
        }

        public Employee Add(Employee employee)
        {
            employee.Id = _employeList.Max(e => e.Id) + 1;
            _employeList.Add(employee);
            return (employee);
        }

        public IEnumerable<Employee> GetAllEmployees()
        {
            return _employeList;
        }

        public Employee GetEmployee(int Id)
        {
            return _employeList.FirstOrDefault(e => e.Id == Id);
        }
    }
}

Dept.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EmplloyeeManagement.Models
{
    public enum Dept
    {
        None,
        HR,
        Networking,
        Developer

    }
}

In Controller Folder add one Controller like “Home”
HomeController.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using EmplloyeeManagement.Models;
using EmplloyeeManagement.ViewModels;

namespace EmplloyeeManagement.Controllers
{
    public class HomeController : Controller
    {
        private readonly IEmployeeRepostory _employeeRepository;
        public HomeController(IEmployeeRepostory employeeRepostory)
        {
            _employeeRepository = employeeRepostory;

        }
        public ViewResult Index()
        {
            var model = _employeeRepository.GetAllEmployees();
            return View(model);
        }
        public ViewResult Details(int? id)
        {
            HomeDetailsVewModel homeDetailsVewModel = new HomeDetailsVewModel()
            {
                Employee = _employeeRepository.GetEmployee(id ?? 1),
                PageTitle = "From How Controller Details View"

            };

            return View(homeDetailsVewModel);
        }

        [HttpGet]
        public ViewResult Create()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                Employee newEmployee = _employeeRepository.Add(employee);
                return RedirectToAction("Details", new { id = newEmployee.Id });
            }
            return View();
        }

    }
}

In View Folder add Index and Details.cshtml page
Index.cshtml

div class="card-deck">
	@foreach (var employee in Model)
	{
		<div class="card m-3">
			<div class="card-header">
				<h3>@employee.Name</h3>
			</div>
			@*<img class="card-img-top" src="~/images/Hello.jpg" asp-append-version="true" />*@
			<div class="card-footer text-center">
				@*Tag helper*@
         <a asp-controller="home" asp-action="details" asp-route-id="@employee.Id" class="btn btn-primary m-1">View</a>
		 </div>
		</div>
	}

</div> 

Details.cshtml

<div class="row justify-content-center m-3">
	<div class="col-sm-8">
		<div class="card">
			<div class="card-header">
				<h1>@Model.Employee.Name</h1>
			</div>
			<div class="card-body text-center">
				@*<img class="card-img-top" src="~/images/Hello.jpg" asp-append-version="true" />*@
				<h4>Employee ID :@Model.Employee.Id</h4>
				<h4>Email :@Model.Employee.Email</h4>
				<h4>Department:@Model.Employee.Department</h4>
			</div>
			<div class="card-footer text-center">
				@*Tag Helpers*@
				<a asp-controller="home" asp-action="index" class="btn btn-primary">Back</a>
				</div>
		</div>
	</div>

</div>

Output:
tag-helpers-asp-net-core-mvc
tag-helpers-asp-net-core-mvc

Leave a Reply

Your email address will not be published. Required fields are marked *