why i love tag helpers

tag helpers were introduced in asp.net core which enable server-side code to participate in creating and rendering html elements in razor files.

Tags: Technology, .NET Core, ASP.NET
Posted by mjourdan on September 10, 2019

Tag Helpers were introduced in ASP.NET Core which enable server-side code to participate in creating and rendering HTML elements in Razor files. I find them to be a happy addition and plan to use them. Here is an example to get you started using them too!

label example

Let's say this is your model

public class MyModel {
	public string Email { get; set; }
}

In ASP.NET MVC you would create a label like this:

@Html.LabelFor(m => m.Email, new { @class = “col-md-2 control-label })

Which generates some HTML like this:

<label for="Email" class="col-md-2 control-label"></label>

Now in an ASP.NET Core MVC razor file, you only need to do this! It will bind to the email property on the model for you.

<label asp-for="Email" class="col-md-2 control-label"></label>

The tag helper asp-for does its magic in the background to bind to the Email property on your model.

anchor tag helper

Generating a link to an internal page looks so much cleaner. By using the anchor tag helper you can quickly set the destination of a hyperlink. You just set the controller, action and area.

<a class="dropdown-item" asp-area="" asp-controller="Home" asp-action="Index">My Home Page</a>

form comparison

final thoughts:

I found the tag helper to be a great addition to the framework and something I plan to use going forward.

  • The code looks cleaner and easier to read.
  • The tag helpers follow HTML standards with less magic, looks like standard HTML.
  • Allows for more functionality and control of the expected HTML because the tag helper will plug itself right into the standard HTML

Hop on over to Microsoft's documentation for a in depth look at tag helpers in ASP.NET Core