Tag Helpers in ASP.Net Core MVC

In this article, we will learn about Tag Helpers in .NET Core MVC.

Tag Helpers is new feature introduced in ASP.Net Core MVC. Tag Helpers do the same thing as HTML Helpers does in previous versions of MVC but with a variety of changes.

What are Tag Helpers?

Tag Helpers helps server side code to create and render HTML tags in Razor View engine.
Tag Helpers provide an HTML friendly development experience and is totally different from HTML helpers. Tag Helpers enable IntelliSense, which allow to build HTML markup in easy way. Tag helpers is a new feature in ASP.Net Core MVC. Tag Helpers can be used to define custom tags as well.

HTML Helpers vs Tag Helpers

The syntax in Tag helpers is completing different than HTML helper.

In HTML Helpers –

@Html.Label("Product Name")
@Html.TextBoxFor(model => model.ProductName, new { placeholder = "IPhone7" })

You may check this blog to know more about HTML Helpers – HTML Helper in MVC

In Tag Helpers –

If you have created an Empty ASP.Net Core Project.

Then you have to install couple of packages using Package Manager Console.

1. install-package Microsoft.AspNetCore.MVC

2. PM> install-package Microsoft.AspNetCore.MVC.Taghelpers

If you have selected Web Application (Model-View-Controller), then in this case you do not have to install these packages.
Now Add this line at the top in View.

@addTagHelper “*,Microsoft.AspNetCore.Mvc.TagHelpers”
Now you may write below tags, where ProductName is one of the property from a Model class.

<label asp-for="ProductName"></label>
<input type="text" asp-for="ProductName" />

In below screen, you may see how intellisense works with asp-for expression.

Tag Helpers in Core MVC
    <label asp-for="ProductName"></label>
    <input type="text" asp-for="ProductName" />
    <label asp-for="ProductCost"></label>
    <input type="text" asp-for="ProductCost" />
    <input type="submit" value="Save Product" />

Built in Tag Helpers in Core MVC

There are various built-in Tag Helpers to achieve common tasks.
For eg – To create a link to a particular action of a particular controller.

<a asp-controller="User" asp-action="Login">Login Here</a>

You may like other blog on Core MVC-

Introduction to ASP.Net Core MVC

Leave a Comment

RSS
YouTube
YouTube
Instagram