Site icon Tutexchange

New Tag Helpers in ASP.Net Core

Advertisements

New Tag Helpers in ASP.Net Core

Any web application we develop the end output is always an HTML if we see back to OLD ASP.NET webforms stack then we use to have server controls which help us to render HTML as output then Microsoft releases new ASP.NET MVC framework 2009 which came up with new HTML helper to render HTML. Again,
Microsoft release New ASP.NET Core framework in 2016 which had Html helper and New tag helper in it.

Why New tag helpers if we had HTML helper already in HTML helper, we had issues to apply a style to controls because we won’t get intelligence while applying it to over this issue, we have new Tag Helpers.

Let’s Create a simple ASP.NET Core Web Application project to see a demo of how to use New Tag Helpers in a simple way.

Creating ASP.NET Core Application

We are going to choose “ASP.NET Core Web Application” template for project and name this project as WebApplication3. 

List of Tag Helpers

  1. Label Tag Helper
  2. Input Tag Helper
  3. Checkbox
  4. Radio button
  5. Select Tag Helper (Dropdown List)
  6. Textarea Tag Helper
  7. Anchor Tag Helper
  8. Image Tag Helper
  9. The Form Tag Helper

After choosing template click on the Next button you will see “configure your new projectdialog here you can configure project name, location of project and solution name after configuring click on Next button.

Again, you will see a new dialog with framework selection options along with template selection.

Here we are going to choose the .Net Core framework and ASP.NET core 3.0 framework and in the template, we are going to choose Web Application and click on create button to create an application with custom configuration.

Now the project is ready for a demo now let’s start with it.

This is a basic project structure which comes with a default home controller and few views and layout to start the project.

The first thing to understand how a tag helper work is to see how it is a trigger from where it is triggered.

Tag helper is located in the Views/Shared folder which applies to all Views in Views folder.

If you want different _ViewImport.cshtml file for each folder then you can add _ViewImport.cshtml file in each folder. After you add _ViewImport.cshtml in the folder it will apply to all Views in that folder.

Tag helper is triggered from _ViewImport.cshtml file in which is new in ASP.NET Core let’s understand what is _ViewImport.cshtml does.

When we declare strongly type model on View, we need to provide a namespace for it then we can access it right, and also it won’t look good for reading file also.

@model WebApplication3.Models.Product
@{
    ViewData["Title"] = "Home Page";
}

Using _ViewImport.cshtml file we can remove namespace of a model by writing that namespace in _ViewImport.cshtml file as shown below.

After adding the namespace in _ViewImport.cshtml file we can just give the model name on View which looks clean.

@model Product
@{
    ViewData["Title"] = "Home Page";
}

Enables Tag helper

Now to use built-in tag helper in asp.net core you must see _ViewImport.cshtml file you will find a tag called @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers this tag enables Tag Helper on View in the entire application.

Now we got an idea where is tag helper located and how it is enabled New let’s add Controller, Action Method and View to see it in action.

We are going to add a controller with Name ‘Registration‘ Controller and inside that, we have changed the action method name from the index to Register.

using Microsoft.AspNetCore.Mvc;

namespace WebApplication3.Controllers
{
    public class RegistrationController : Controller
    {
        public IActionResult Register()
        {
            return View();
        }
    }
} 

Next Let add Model with name “RegistrationModel” in Models folder. With 2 properties in it further we are going to keep adding more properties to this Model.

namespace WebApplication3.Models
{
    public class RegistrationModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

After adding RegistrationModel next we are going to add View for action method Register.

Next, on Register View, we are going first add 2 input and labels controls with new tag helper syntax.

Creating Label Tag Helper

Creating Input Tag Helper

CSHTML

@model RegistrationModel
@{
    ViewData["Title"] = "Register";
}

<h1>Register</h1>

<label asp-for="FirstName"></label>
<input asp-for="FirstName" class="form-control" />
<br />

<label asp-for="LastName"></label>
<input asp-for="LastName" class="form-control" />

HTML

<label for="FirstName">FirstName</label>
<input class="form-control" type="text" id="FirstName" name="FirstName" value="">
<br>
<label for="LastName">LastName</label>
<input class="form-control" type="text" id="LastName" name="LastName" value="">

If you see we get intelligence while writing style and apply CSS to input controller which was not there in html helper of the razor syntax.

After creating a label and input helper and applying CSS and style next we are going to add a checkbox.

Input Tag Helper (Checkbox)

We are going to use same Input tag helper to create checkbox just we need to add an HTML type attribute to Input tag helper.

For adding a checkbox, I have added Boolean property IsDeveloper to Model

namespace WebApplication3.Models
{
    public class RegistrationModel
    {
        public bool IsDeveloper { get; set; }
    }
}

For making Input control as checkbox we need to set HTML type attribute as a checkbox

CSHTML

<input asp-for="IsDeveloper" type="checkbox" />

HTML

<input type="checkbox" 
data-val="true" 
data-val-required="The IsDeveloper field is required." 
id="IsDeveloper" 
name="IsDeveloper" 
value="true">

Input Tag Helper (Radio)

We are going to use same Input tag helper to create radio button just we need to add HTML type attribute as a radio to Input tag helper.

For adding a radio button, I have added string property Gender to Model.

namespace WebApplication3.Models
{
    public class RegistrationModel
    {
        public string Gender { get; set; }
    }
}

CSHTML

<label>Gender</label>
<br />
<input asp-for="Gender" value="Male" type="radio" /> Male
<input asp-for="Gender" value="Female" type="radio" /> Female

HTML

Select Tag Helper (Dropdown List)

We are going to add select tag helper on same register view. For doing that first we are going to create a list of SelectListItem for assign collection to select tag helper and also, we are going to add integer property for getting the selected item.

Properties added to Model

using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;

namespace WebApplication3.Models
{
    public class RegistrationModel
    {
        public int? CountryId { get; set; }
        public List<SelectListItem> ListofCountries { get; set; }
    }
}

After adding properties next we are going to initialize Registration Model class in Register action method and send that model to view for binding controls.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using WebApplication3.Models;

namespace WebApplication3.Controllers
{
    public class RegistrationController : Controller
    {
        public IActionResult Register()
        {
            RegistrationModel registrationModel = new RegistrationModel()
            {
                ListofCountries = new List<SelectListItem>()
                {
                    new SelectListItem
                    {
                        Value = "",
                        Text = "Select"
                    },
                    new SelectListItem
                    {
                         Value = "1",
                        Text = "Country 1"
                    },
                    new SelectListItem
                    {
                         Value = "2",
                        Text = "Country 2"
                    }
                }
            };
            

            return View(registrationModel);
        }
    }
}

Next, we are going to add the select tag and assign a list of countries collection to it.

An asp-for attribute generates the id and names HTML attributes for the expression name specified in it.

If you see below, we have assigned “CountryId” to asp-for attribute and “Model.ListofCountries” to asp-items along with that we have added CSS class to Select Tag Helper.

HTML

<select asp-for="CountryId" class="form-control" asp-items="Model.ListofCountries"></select>

CSHTML

@model WebApplication3.Models.RegistrationModel
@{
    ViewData["Title"] = "Register";
}

<h1>Register</h1>

<label asp-for="FirstName"></label>
<input asp-for="FirstName" class="form-control" />
<br />
<label asp-for="LastName"></label>
<input asp-for="LastName" class="form-control" />
<br />
<label>Countries</label>
<select asp-for="CountryId" class="form-control" asp-items="Model.ListofCountries"></select>

Next, we are going to run the application to see how to select tag helper renders in the browser.

Textarea Tag Helper

Textarea Tag Helper is similar to input tag helper.
We adding Textarea tag helper we are going to add Address property to ‘RegistrationModel” class.

using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;

namespace WebApplication3.Models
{
    public class RegistrationModel
    {
        public string Address { get; set; }
    }
}

Next, on Register view, we are going to add Textarea.
It is similar to input control just we need to set an asp-for attribute with model property “Address“.

HTML

<textarea class="form-control" asp-for="Address"></textarea>

CSHTML

@model WebApplication3.Models.RegistrationModel
@{
    ViewData["Title"] = "Register";
}

<h1>Register</h1>
<div class="row">
    <div class="col-md-3">
        <label asp-for="Address"></label>
        <textarea class="form-control" asp-for="Address"></textarea>
    </div>
</div>

Next, we are going to run the application to see how TextArea tag helper rendered in the browser.

HTML Rendered

<textarea class="form-control" id="Address" name="Address"></textarea>

Anchor Tag Helper

Creating basic link using new anchor tag helper we need to pass controller name, action name.

<a asp-controller="Registration" asp-action="Register">Registration Page</a>

HTML

<a href="/Registration/Register">Registration Page</a>

CSHTML

@model WebApplication3.Models.RegistrationModel
@{
    ViewData["Title"] = "Register";
}

<h1>Register</h1>
<div class="row">
    <div class="col-md-3">
        <a asp-controller="Registration" asp-action="Register">Registration Page</a>
    </div>
</div>

Added a simple link on View

If you want to pass data {id?} place holder which is defined in default route template using new anchor tag.

Default Route

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

HTML

<a href="/Registration/Information/1">Information about Registration</a>

CSHTML

<a asp-controller="Registration"
           asp-action="Information"
           asp-route-id="@Model.InformationId">Information about Registration</a>

Anchor tag rendered on View

Reading Value from route id placeholder

Passing Parameters other than route id

CSHTML

<a asp-controller="Registration"
   asp-action="Information"
   asp-route-InformationId="@Model.InformationId">Information</a>

HTML

<a href="/Registration/Information?InformationId=1">Information</a>

Image Tag Helper

Image tag helper helps us to render image but one good thing about this helper is it has cache busting feature built-in init.

Many times, you have update images of your website and your client says they are not able to see new images because images are cached they need to clear cache of images then they are able to see it right this new feature of Image tag helper will help you to clear cache without clear cache of your website manual. 

Let see how to use it. To render an image, we must have an image located somewhere right in asp.net core whatever static content you want to use such as CSS, JavaScript files, images it must be stored inside wwwroot folder.

CSHTML

For using the cache busting feature, we need to add asp-append-version attribute to image tag helper and set it to true.

<img src="~/Images/coffee.jpg" height="100px" width="100px" asp-append-version="true" alt="coffee" />

HTML

When we set an asp-append-version attribute to true then image tag helper appends v parameter which is a hash string of image file. when you will change src of this image tag helper a new hash string will be calculated and appended as v parameter due to this the cache of old image tag is removed.

The Form Tag Helper

This Form tag helper form tag for forming that we need to pass asp-controller attribute and asp-action attribute method name and method (GET or POST).

CSHTML

<form asp-controller="Registration" asp-action="Register" method="post">
</form>

List of Attribute which can be used with the form tag.

Attribute Description
asp-controller The name of the controller.
asp-action The name of the action method.
asp-area The name of the area.
asp-page The name of the Razor page.
asp-page-handler The name of the Razor page handler.
asp-route The name of the route.
asp-route-{value} A single URL route value. For example, asp-route-id=”1234″.
asp-all-route-data All route values.
asp-fragment The URL fragment.

Reference from:- https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-3.0

Exit mobile version