Tag helpers demo in ASP.NET Core
We are going to implement a simple register user page using ASP.NET Core and MVC to demonstrate Tag Helpers. Traditionally developers use or have used ASP.NET 4.x framework to create web apps. But ASP.NET Core is a redesign of ASP.NET 4.x, including architectural changes that result in a leaner, more modular framework.
ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, Internet-connected apps.
ASP.NET Core MVC provides several new features to build web apps , out of which we are going to focus on Tag Helpers .
Following is an example of Tag helper.
<div class=”form-group row”>
<label asp-for=”Username“ class=”col-sm-2 col-form-label”></label>
<div class=”col-sm-10″>
<input asp-for=”Username“ class=”form-control” >
<span asp-validation-for=”Username“ class=”text-danger”></span>
</div>
</div>
In above example asp-for and asp-validation-for are Tag Helpers. Tag Helpers provide an HTML-friendly development experience. For the most part, Razor markup using Tag Helpers looks like standard HTML. Front-end designers conversant with HTML/CSS/JavaScript can edit Razor without learning C# Razor syntax.
In above example, each of the “asp-“ attributes has a value of “Username“, but “Username“, but “Username” isn’t a string. In this context, “Username“ is the C# model expression property for the User model. So you can understand how easily Tag Helpers can be written within HTML tags without any Razor expression.
Traditionally we were using HTML Helpers for the same. Following is an example of same code with the help of HTML Helpers.
<div class=”form-group row”>
@Html.LabelFor(m=>m.Username,“User Name”,
new { @class=“col-sm-2 col-form-label” })
<div class=”col-sm-10″>
@Html.TextBoxFor(m => m.Username, “User Name”,
new { @class = “form-control” })
@Html.ValidationMessageFor(m => m.Username, “”,
new { @class = “text-danger” })
</div>
</div>
In above example , we see multiple explicit transitions between HTML and C# in Razor views with the help of @ symbol. Tag Helpers reduce the explicit transitions between HTML and C# in Razor views.
Also .NET CORE has provided A rich IntelliSense environment for creating HTML and Razor markup. After you enter <label, IntelliSense lists the available HTML/CSS attributes and the Tag Helper-targeted attributes in Visual Studio. IntelliSense statement completion allows you to enter the tab key to complete the statement with the selected value.
Following code snippet shows User registration form created using Tag Helpers.
Though this is an advantage of Tag Helpers over HTML Helper , but it’s important to recognize that Tag Helpers don’t replace HTML Helpers. There’s not a Tag Helper for each HTML Helper.