Tag Helpers

Tag Helpers are a new feature in ASP.NET Core; they help generate HTML elements. In HTML helpers, we will write C#/Razor code to generate HTML. The disadvantage associated with this approach is that many frontend engineers will not know C#/Razor code; they work with plain HTML, CSS, and JavaScript. Tag Helpers look just like HTML code, but have all the features of server-side rendering. You can even build custom Tag Helpers as per your needs. The advantage of Razor over Tag helpers is that while Tag Helpers are more frontend-developer friendly, sometimes we might need the power of Razor, as it is a powerful programming model. 

Let's take a look at how to use a Tag Helper. The Tag Helpers package is already included in the Microsoft.AspNet.Core.All NuGet package.

Remember, we have already added Tag Helpers support to the ViewImports file in the preceding section.

Had we included the _ViewImports.cshtml file under the Home folder, Tag Helpers would be available only for the views under the Home folder. So, we should use the root of the view folder.

Let's add a simple action method called Index3 in the HomeController file, and in the associated view, we will use Tag Helpers, as shown in the following code:


Go to https://goo.gl/zwYvmh to access the code.
public IActionResult Index3()
{
ViewBag.Title = "This is Index3";
Person person = new Person();
return View(person);
}

Add the corresponding view (the Index3.cshtml file) for the Index3 action method with the following code:

@model Lesson3.Models.Person
<form asp-controller="Home" asp-action="Index3">
<table>
<tr>
<td><label asp-for ="Name">Name</label></td>
<td><input asp-for="Name" /></td>
</tr>
<tr>
<td><label asp-for ="Age">Age</label></td>
<td><input asp-for ="Age" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form>

The following are a few things that you need to note in the preceding code for the use of Tag Helpers: