Introduction to Tag Helpers in ASP.NET Core

Introduction to Tag Helpers in ASP.NET Core

Tag Helpers are a new addition in ASP.NET Core MVC, they are used to perform defined transformations on HTML elements. With Tag Helpers you can enable server-side code to participate in creating and rendering the HTML elements in Razor files.

Tag Helpers are of 2 types:

  • 1. Built-In Tag Helpers – that comes pre-built in the Core Framework, and perform common tasks like creating forms, showing validation messages, etc.
  • 2. Custom Tag Helper – that can be created by you to perform your desired transformation on an HTML element.

First you will look into Built-In tag helpers then I will explain how to create your own Custom Tag Helper.

Creating an Application to understand Tag Helpers

Start by creating a new ASP.NET Core Web Application in your Visual Studio 2017. Name this application ‘TagHelpers’. Select the Empty Template, framework as .NET Core and version as ASP.NET Core 2.0.

Change the Startup.cs content as highlighted by the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace TagHelpers
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseDeveloperExceptionPage();
            app.UseStatusCodePages();
            app.UseStaticFiles();
            app.UseMvc(routes =>
            {
                // Default Route
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Add bower.json

Add bower.json file in the root of your application. Add “bootstrap”: “v4.1.3” inside the dependencies node as shown in the code below:

{
  "name": "asp.net",
  "private": true,
  "dependencies": {
    "bootstrap": "v4.1.3"
  }
}

Save the file by pressing ‘Ctrl+S’ and this will make bower to download the bootstrap package to your application.
In a few seconds time bootstrap package will be added to your application which you can find inside the ‘wwwroot/lib’ folder.

Add Model

Create a ‘Models’ folder in the root of the application and add class ‘Products.cs’ in it. Add the following code to the class:

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

namespace TagHelpers.Models
{
    public class Product
    {
        public string Name { get; set; }
        public float Price { get; set; }
        public int Quantity { get; set; }
    }
}

Now add a ‘Repository.cs’ class inside the ‘Models’ folder with the code given below:

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

namespace TagHelpers.Models
{
    public interface IRepository
    {
        IEnumerable<Product> Products { get; }
        void AddProduct(Product newProduct);
    }

    public class ProductRepository : IRepository
    {
        private List<Product> products = new List<Product> {
            new Product { Name = "Men Shoes", Price = 99.99F, Quantity= 100},
            new Product { Name = "Women Shoes", Price = 199.99F, Quantity= 200},
            new Product { Name = "Children Games", Price = 299.99F, Quantity= 300},
            new Product { Name = "Coats", Price = 399.99F, Quantity= 400},
        };

        public IEnumerable<Product> Products => products;
        public void AddProduct(Product newProduct)
        {
            products.Add(newProduct);
        }
    }
}

The repository class has an IRepository Interface which contains two members –

  • 1. An ienumerable property for iterating over all products.
  • 2. A function to add products.

The repository class also has a ‘ProductRepository’ class that implements the IRepository Interface. The work of the ProductRepository is to provide with a repository of product to the application.

It stores products in a private list (by name ‘products’) and also has a method ‘AddProduct’ to add new products to the private list.

It also has an ienumerable property for iterating over the products (by name ‘Products’).

Register Repository as a Service

Go to the Startup class and registers the repository as a service using the singleton life cycle. This will help controllers to fetch the products from the repository without creating its object. This feature is known as Dependency Injection which I will explain you in details in the Dependency Injection Tutorial.

The change to make in the Startup class is highlighted in the below code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using TagHelpers.Models;

namespace TagHelpers
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IRepository, ProductRepository>();
            services.AddMvc();
        }

        // Removed for clarity
    }
}

Add Controller

Create a ‘Controllers’ folder in the root of your application and add an Empty Controller to it, name it ‘HomeController’.

Change the HomeController code as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TagHelpers.Models;

namespace TagHelpers.Controllers
{
    public class HomeController : Controller
    {
        private IRepository repository;
        public HomeController(IRepository repo)
        {
            repository = repo;
        }

        public IActionResult Index()
        {
            return View(repository.Products);
        }
    }
}

Notice the constructor which takes an IRepository object. The dependency injection feature will automatically create the object of the ‘ProductRepository’ class when the HomeController is called.

This is done because I registered the ProductRepository class, as a service using the singleton life cycle, in the ConfigureServices method. And I told Core MVC to automatically provide the object of the ProductRepository class whenever some code calls for creating an object of IRepository interface.

The Index Action simply returns the IEnumerable property that contains all the products in the repository.

Add _ViewStart.cshtml, _ViewImports.cshtml

Create a ‘Views’ folder in the root of your application for keeping your View files. Inside this folder add the following 2 files:

_ViewStart.cshtml

@{
    Layout = "_Layout";
}

_ ViewImports.cshtml

@using TagHelpers.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

The @addTagHelper makes Built-In Tag Helpers, that are defined in an assembly called Microsoft.AspNetCore.Mvc.TagHelpers, available in the application.

I have also imported the ‘TagHelpers.Models’ namespace so that I don’t have to import it on my views.

Create Layout File

Create a ‘Shared’ folder inside the Views folder and inside this folder add ‘_ Layout.cshtml’ file. Change the code of the file with the highlighted code as shown below:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
</head>
<body>
    <div class="container-fluid">
        @RenderBody()
    </div>
</body>
</html>

Notice I have added the reference of bootstrap.css file in the head section of the layout. I have also given a bootstrap class to the div class=”container-fluid” that contains the @RenderBody() section.

Add View

Create another folder ‘Home’ inside the ‘Views’ folder. Next Add ‘Index’ View in the ‘Home’ folder with content as given below:

@model IEnumerable<Product>

<table class="table table-sm table-bordered">
    <thead class="bg-dark text-white">
        <tr>
            <th>Name</th>
            <th>Price</th>
            <th>Quantity</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var product in Model)
        {
            <tr>
                <td>@product.Name</td>
                <td>@product.Price</td>
                <td>@product.Quantity</td>
            </tr>
        }
    </tbody>
</table>

You may remember that the Index action of the Home controller returns an IEnumerable type that contains all the products in the repository. Therefore in this view i have declared my Model as IEnumerable type. Then I am simply showing all the products in an HTML table.

Notice the code inside the ‘tbody’ where I am looping through all the products to create a separate ‘tr’ element for each of them.

The CSS classes used inside the ‘table’ and ‘thead’ are Bootstrap classes for giving them text color, border and background color.

Run your application and you will see all products displayed by the View. See the below image:

all products

Conclusion

Now you are ready to Tag Helpers by implementing them in this application. Now check the next tutorial on Tag Helpers – Built-In Tag Helpers in ASP.NET Core.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.