Writing a custom TagHelper in ASP.NET 5

Reading Time: 6 minutes

ASP.NET 5 brings some new features to MVC. One of these features is TagHelpers, which allow us to add new attributes to HTML tags (or create custom tags altogether) to add behavior to these tags. At this moment – beta8 – we receive the following TagHelpers out of the box:

– AnchorTagHelper: allows you to write <a asp-controller=”Home” asp-action=”Index”>Back to home</a> instead of @Html.ActionLink(“Back to home”, “Index”, “Home”)
– LabelTagHelper, InputTagHelper, TextAreaTagHelper, SelectTagHelper, etc.: instead of writing Razor like @Html.LabelFor(m => m.Property1, new { @class = “control-label col-md-2”}), you can use a syntax which is much cleaner: <label asp-for=”Property1″ class=”control-label col-md-2″></label>
– EnvironmentTagHelper: adds a new tag, <environment>, giving you the possibility to include <link> or <script> tags specific for Development or Production environments.
– LinkTagHelper, ScriptTagHelper: adds attributes to <link> and <script> to allow the use of CDN’s and fallback urls.

This list is incomplete, but you can head over to GitHub to see every available TagHelper class currently available.

You can also create your own TagHelper classes. I’ll show you an example which enables you to do this:

That img tag would load a users profile image using the ProfileImage action method in a UsersController class: userful for retrieving a profile image from a blob container on Azure, for example.

Continue reading “Writing a custom TagHelper in ASP.NET 5”