ASP.NET Core - Razor Tag Helpers



Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. Tag helpers are a new feature and similar to HTML helpers, which help us render HTML.

  • There are many built-in Tag Helpers for common tasks, such as creating forms, links, loading assets etc. Tag Helpers are authored in C#, and they target HTML elements based on the element name, the attribute name, or the parent tag.

  • For example, the built-in LabelTagHelper can target the HTML <label> element when the LabelTagHelper attributes are applied.

  • If you are familiar with HTML Helpers, Tag Helpers reduce the explicit transitions between HTML and C# in Razor views.

In order to use Tag Helpers, we need to install a NuGet library and also add an addTagHelper directive to the view or views that use these tag helpers. Let us right-click on your project in the Solution Explorer and select Manage NuGet Packages....

Manage NuGet Packages

Search for Microsoft.AspNet.Mvc.TagHelpers and click the Install button.

You will receive the following Preview dialog box.

Preview Dialog Box

Click the OK button.

License Acceptance

Click the I Accept button. Once the Microsoft.AspNet.Mvc.TagHelpers is installed, go to the project.json file.

{ 
   "version": "1.0.0-*", 
   "compilationOptions": { 
      "emitEntryPoint": true 
   },  
   
   "dependencies": { 
      "Microsoft.AspNet.Mvc": "6.0.0-rc1-final", 
      "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final", 
      "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", 
      "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", 
      "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final", 
      "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final", 
      "EntityFramework.Commands": "7.0.0-rc1-final", 
      "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final" 
   },  
   
   "commands": { 
      "web": "Microsoft.AspNet.Server.Kestrel", 
      "ef": "EntityFramework.Commands" 
   },  
   
   "frameworks": { 
      "dnx451": { }, 
      "dnxcore50": { } 
   },  
  
   "exclude": [ 
      "wwwroot", 
      "node_modules" 
   ], 
  
   "publishExclude": [ 
      "**.user", 
      "**.vspscc" 
   ] 
}

In the dependencies section, you will see that "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final" is added.

  • Now anybody can author a tag helper, so if you can think of a tag helper that you need, you can write your own tag helper.

  • You can place it right inside your application project, but you need to tell the Razor view engine about the tag helper.

  • By default, they are not just rendered down to the client, even though these tag helpers look like they blend into the HTML.

  • Razor will call into some code to process a tag helper; it can remove itself from the HTML and it can also add additional HTML.

  • There are many wonderful things that you can do with a tag helper, but you need to register your tag helpers with Razor, even the Microsoft tag helpers, in order for Razor to be able to spot these tag helpers in the markup and to be able to call into the code that processes the tag helper.

  • The directive to do that is addTagHelper, and you can place this into an individual view, or if you plan on using tag helpers throughout the application, you can use addTagHelper inside the ViewImports file as shown below.

@using FirstAppDemo.Controllers 
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers" 

The syntax to register all the tag helpers that are in an assembly is to use asterisk comma (*,) and then the assembly name, Microsoft.AspNet.Mvc.TagHelpers. Because the first piece here is a type name, this is where we could list a specific tag helper if you only wanted to use one.

But if you just wanted to take all the tag helpers that are in this assembly, you can just use the asterisk(*). There are many tag helpers available in the tag helper library. Let us have a look at the Index view.

@model HomePageViewModel  
@{  
   ViewBag.Title = "Home"; 
} 
<h1>Welcome!</h1> 

<table> 
   @foreach (var employee in Model.Employees) { 
      <tr> 
         <td>
            @Html.ActionLink(employee.Id.ToString(), "Details", new { id = employee.Id })
         </td> 
         <td>@employee.Name</td> 
      </tr> 
   } 
</table>

We already have an HTML helper using the ActionLink to generate an anchor tag that will point to a URL that allows us to get to the details of an employee.

Let us first add the Details action in the home controller as shown in the following program.

public IActionResult Details(int id) { 
   var context = new FirstAppDemoDbContext(); 
   SQLEmployeeData sqlData = new SQLEmployeeData(context); 
   var model = sqlData.Get(id); 
   
   if (model == null) { 
      return RedirectToAction("Index"); 
   } 
   return View(model); 
} 

Now we need to add a view for the Details action. Let us create a new view in the Views → Home folder and call it Details.cshtml and add the following code.

@model FirstAppDemo.Models.Employee 
<html xmlns = "http://www.w3.org/1999/xhtml"> 
   <head> 
      <title>@Model.Name</title> 
   </head> 
   
   <body> 
      <h1>@Model.Name</h1> 
      <div>Id: @Model.Id</div> 
      
      <div> 
         @Html.ActionLink("Home", "Index") 
      </div> 
      
   </body> 
</html>

Let us now run the application.

Razor Tag Helpers Application Run

When you click on the ID of an employee then it will get you to the details view.

Let us click the first employee ID.

First Employee Id

Now to use tag helper for this, let us add the following line in the index.cshtml file and remove the HTML helper.

<a asp-action = "Details" asp-rout-id = "@employee.Id" >Details</a> 

The asp-action = "Details" is the name of the action that we want to get to. If there is any parameter that you want to be passed along, you can use the asp-route tag helper and here we want to include ID as parameter so we can use asp-route-Id taghelper.

The following is the complete implantation of index.cshtml file.

@model HomePageViewModel  
@{  
   ViewBag.Title = "Home"; 
} 
<h1>Welcome!</h1> 

<table> 
   @foreach (var employee in Model.Employees) { 
      <tr> 
         <td> 
            <a asp-action="Details" asp-route-id="@employee.Id" >Details</a> 
         </td> 
         <td>@employee.Name</td> 
      </tr> 
   } 
</table> 

Let us run your application again. After you run the application, you will see the following page.

Employee Details

Previously, we were displaying the ID as the linking text, but now we are showing the text Details. Now, we click on the details and are creating the correct URL now using the tag helpers instead of the HTML helpers.

Html Helpers Tag

Whether you choose to use HTML helpers or tag helpers, it's really a matter of personal preference. Many developers find tag helpers to be easier to author and maintain.

Advertisements