Saturday 29 August 2020

Tag Helpers ASP.NET Core

 What are Tag Helpers

Tag Helpers are server side components. They are processed on the server to create and render HTML elements in Razor files. If you have any experience with previous version of ASP.NET MVC, then you may be familiar with HTML helpers. Tag Helpers are similar to HTML helpers. There are many built-in Tag Helpers for common tasks such as generating links, creating forms, loading assets etc.

Importing built-in Tag Helpers

To make the built-in tag helpers available for all the views in our entire application, import the tag helpers using _ViewImports.cshtml file. To import tag helpers we use @addTagHelper directive.

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

The wildcard * indicates that we want to import all the tag helpers.

Microsoft.AspNetCore.Mvc.TagHelpers is the assemly that contains the built-in tag helpers

Generating Links using Tag Helpers

Let's say we want to view a specific employee details. So we want to generate the following hyperlink. The number 5 is the ID of the employee whose details we want to view.

/home/details/5

There are several ways we could do this in a razor view

Option 1 : Manually generating the links

@foreach (var employee in Model)
{
    <a href="/home/details/@employee.Id">View</a>
}


Option 2 :
Using HTML helpers

@Html.ActionLink("View""details"new { id = employee.Id })


generates an anchor element

<a href="/hom/details/5">View</a>

@Url.Action("details""home"new { id = employee.Id })


generates a string

/hom/details/5

Option 3 : Using Tag Helpers

<a asp-controller="home" asp-action="details" asp-route-id="@employee.Id">View</a>

generates

<a href="/Home/details/5">View</a>


Anchor Tag Helper

The Anchor Tag Helper enhances the standard HTML anchor (<a ... ></a>) tag by adding new attributes such as 

asp-controller
asp-action
asp-route-{value}

The rendered anchor element's href attribute value is determined by the values of these asp- attributes. 

As the names imply asp-controller specifies the controller name and asp-action specifies the action name to include in the generated href attribute value. asp-route-{value} attribute is used to include route data in the generated href attribute value. {value} can be replaced with the route parameters such as id for example.

<a asp-controller="home" asp-action="details" asp-route-id="@employee.Id">View</a>

Advantage of using Tag helpers
Tag helpers generate links based on the application routing templates. This means if we later change routing templates, the links generated by tag helpers will automatically reflect those changes made to the routing templates. The generated links just work. 

Where as if we have hard-coded the URL paths manually, we would have to change the code in lot of places when the application routing templates change. Click here

ASP.NET Core Image tag helper
Image Tag Helper can help us achieve this. To use the Image tag helper, include asp-append-version attribute and set it to true.

<img src="~/images/noimage.jpg" asp-append-version="true" />

Image Tag Helper enhances the <img> tag to provide cache-busting behavior for static image files. Based on the content of the image, a unique hash value is calculated and is appended to image URL. This unique string prompts the browser to reload the image from the server and not from the browser cache.

<img class="card-img-top"
src="/images/noimage.jpg?v=IqNLbsazJ7ijEbbyzWPke-xWxkOFaVcgzpQ4SsQKBqY" />

Each time the image on the server changes a new hash value is calculated and cached. If the image has not changed the hash isn't recalculated. Using this unique hash value, the browser keeps track of whether the image content on the server has changed. Click here

ASP.NET Core Environment Tag Helper
Environment tag helper supports rendering different content depending on the application environment. The application environment name is set using using ASPNETCORE_ENVIRONMENT variable.

This example loads the non-minified bootstrap css file, if the application environment is "Development"

<environment include="Development">
    <link href="~/lib/bootstrap/css/bootstrap.css" rel="stylesheet" />
</environment>

This example loads the minified bootstrap css file from the CDN (Content Delivery Network), if the application environment is "Staging" or "Production".

<environment include="Staging,Production">
    <link rel="stylesheet"
            href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
            crossorigin="anonymous">
</environment>

"include" attribute accepts a single hosting environment name or a comma-separated list of hosting environment names. On the <environment> tag helper, we also have "exclude" attribute. The content of the <environment> tag is rendered when the hosting environment doesn't match an environment listed in the exclude attribute value.

The "integrity" attribute on the <link> element is used for Subresource Integrity check. Subresource Integrity (SRI for short), is a security feature that allows a browser to check if the file being retrieved has been maliciously altered. When the browser downloads the file, it recalculates the hash and compares it against the "integrity" attribute hash value. If the hash values match, the browser allows the file to be downloaded otherwise it is blocked. Click here

Form tag helpers in asp.net core

We use the following common tag helpers to create a form in ASP.NET Core.  Click here for more
  • Form Tag Helper
  • Label Tag Helper
  • Input Tag Helper
  • Select Tag Helper
  • Textarea Tag Helper
Form Tag Helper:
<form asp-controller="home" asp-action="create" method="post">
</form>

Input Tag Helper:
The Input Tag Helper binds an HTML <input> element to a model expression in your razor view.

@model Employee

<input asp-for="Name">

Label Tag Helper:
The Label Tag Helper generates a label with for attribute. The for attribute links the label with it's associated input element. Consider the following example.

<label asp-for="Name"></label>
<input asp-for="Name">

//The above code generates the following HTML. 

<label for="Name">Name</label>
<input type="text" id="Name" name="Name" value="">

Select Tag Helper:
Generates select element and it's associated option elements.

namespace EmployeeManagement.Models
{
    public enum Dept
    {
        None,
        HR,
        Payroll,
        IT
    }
}

<label asp-for="Department"></label>
<select asp-for="Department"
        asp-items="Html.GetEnumSelectList<Dept>()"></select>

Notice, we are using asp-items tag helper and Html.GetEnumSelectList<Dept>() to get the options for the select element.

Create.cshtml - Complete Code without Bootstrap
@model Employee

@{
    ViewBag.Title = "Create Employee";
}

<form asp-controller="home" asp-action="create" method="post">
    <div>
        <label asp-for="Name"></label>
        <input asp-for="Name" />
    </div>

    <div>
        <label asp-for="Email"></label>
        <input asp-for="Email">
    </div>

    <div>
        <label asp-for="Department"></label>
        <select asp-for="Department"
                asp-items="Html.GetEnumSelectList<Dept>()"></select>
    </div>
    <button type="submit">Create</button>
</form>



0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives