Friday, April 15, 2016

Basic use of TagHelpers in ASP.NET Core


TagHelpers are a great new feature in your MVC Views to assist you in generating HTML code. The advantage is that the syntax is aligned with "normal" HTML elements and attributes. It is a new extension that is handled server-side by Razor, but the code feels more like HTML.

What is the problem with Html.Helpers?

@Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })


This would generate HTML anchor code (<a href>) with specific parameters. One of the issues is the way new objects are created inside the method.

Previously you probably used HtmlHelpers to achieve different stuff in your views, but some stuff was hard to do and looked really bad (in my opinion). One of the things I had a hard time getting used to was applying style to the elements where I used Html Helpers. This is now much more intuitive using Tag Helpers. 


How to use TagHelpers 101


Step1: In your project.json file all you need is the TagHelpers Nuget package. 
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",

Step2: Start replacing HtmlHelpers with TagHelpers in your View files.
In cshtml using Razor you would previously use the @Html.Actionlink and the syntax below.
@Html.ActionLink("This is a link", "About")

Now, using Tag Helpers. In cshtml and Razor you now achieve the same with this syntax.
<a asp-action="About" asp-controller="Home">This is a link</a>

They will produce the same HTML, but I find this syntax to be much more intuitive as it doesn't hide the anchor element/attributes. You will see later that it becomes easier to apply styles etc. on the elements.  

Example Code (asp-controller, asp-action, asp-for, asp-validation-xx)

I picked this small piece of code from my Event handling system where categories are registered using a file similar to the one below. (Views\Category\Create.cshtml). 

@model MFAEvent.Models.Category
@{
    ViewBag.Title = "Create a new category";
}
<h2>@ViewBag.Title</h2>
<form asp-controller="Category" asp-action="Create" method="post" role="form">
    <div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
    <label asp-for="Name"></label>
    <input asp-for="Name" />
    <span asp-validation-for="Name" class="text-danger"></span>             
    <label asp-for="Description"></label>
    <input asp-for="Description" />
    <span asp-validation-for="Description"></span>                                     
    <button type="submit">Create</button>             
</form>     

(bootstrap code is removed from the sample to make it more readable).

Just let me know if you need to entire example and I will post it or mail it to you. :-)