• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Sunday, November 8, 2020

Angular Interpolation

 Admin     November 08, 2020     Angular     3 comments   

In this article, I am going to discuss the Angular Interpolation with Examples. Please read our previous article before proceeding to this article where we discussed the basics of Angular Data Binding. As we already discussed in our previous article, Interpolation Data Binding is used to achieve one way data-binding i.e. From Component to the View Template.

What is Angular Interpolation?
If you want to display the read-only data on a view template (i.e. From Component to the View Template), then you can use the one-way data binding technique i.e. the Angular interpolation.

The Interpolation in Angular allows you to place the component property name in the view template, enclosed in double curly braces i.e. {{propertyName}}. So, the Angular Interpolation is a technique that allows the user to bind a value to a UI element.

Understanding Interpolation in Angular Application:
Let us understand how to use the Interpolation with some examples.
Step1: Modify the index.html
Please modify the index.html file as shown below.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyAngularApp</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>
  
Step2: modify app.component.ts file.
In order to understand Angular Interpolation binding, please have a look at the following image. Here, we have created two string variables (FirstName and LastName) within the component (i.e. AppComponent) and initialize these two variables with some default values. Then please focus on the template property of the @Component decorator. Here, the angular framework gets the value of the FirstName and LastName property from the component (i.e. AppComponent) and then inserts the FirstName and LastName value between the opening and closing <h1> element. Here, we are using double curly braces to place to component properties and this is called Interpolation binding in Angular Application.
Angular Interpolation with Examples
So, open app.component.ts file and then copy and paste the following code in it.
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
    template: `

{{FirstName + ' ' + LastName}}

` }) export class AppComponent { FirstName: string = 'Anurag'; LastName: string = 'Mohanty'; }
And, when you run the application, then it should display the FirstName and LastName in the browser as shown in the below image.
What is Angular Interpolation?
Angular Interpolation with hardcoded string:
It is also possible in Angular to concatenate some hard-coded string value with the property value. In order to understand this, let us add the hard-coded string First Name before the FirstName Property and Last Name before the LastName property. If this is your requirement then you could do this as shown in the below image.
Angular Interpolation with hardcoded string
So, please modify the app.component.ts file as shown below.
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
    template: `

{{ 'First Name : '+ FirstName + ', Last Name : ' + LastName }}

` }) export class AppComponent { FirstName: string = 'Anurag'; LastName: string = 'Mohanty'; }
With the above changes in place, now you should get the FirstName and LastName property values along with the hardcoded string values as shown in the image below.
Angular Interpolation with hardcoded string
Angular Interpolation with Expression:
In Angular using Interpolation (i.e. double curly braces), you can also specify some valid expression. For example, if you want to perform mathematical calculations then you can do such calculations using interpolation as shown in the below image.
Angular Interpolation with Expression
So, modify the app.component.ts file as shown below and then see the output in the browser.
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
    template: `

10 + 5 * 7 - 6 = {{ 10 + 5 * 7 -6 }}

` }) export class AppComponent { }
Output:
Angular Interpolation with Expression
It is also possible in Angular Interpolation to combine the expression with the property value. Let us understand this with an example. Please have a look at the following image. We have Salary property and we need to apply .10 as a bonus. So, here we can combine the expression with the property using Angular Interpolation.
Understanding Interpolation in Angular Application:
So, please modify the app.component.ts file as shown below and see the output.
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
    template: `

Bonus = {{Salary * .10 }}

` }) export class AppComponent { Salary : number = 100000; }
With the above changes in place, now it should display the following output.
Interpolation in Angular Application:
Interpolation in Angular with Ternary Operator:
The expression that is enclosed in the double curly braces is commonly called Template Expression and the template expression can also be a ternary operator. Please modify the app.component.ts file as shown below.
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
    template: `

Last Name : {{ LastName ? LastName : 'Not Available' }}

` }) export class AppComponent { LastName : string = "Mohanty"; }
In the above example, the LastName property has a value i.e. Mohanty, So, you can see the last name property in the browser as shown in the below image.
Interpolation in Angular with Ternary Operator
Now let’s modify the LastName property value to null as shown in the below code and then see the output in the browser.
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
    template: `

Last Name : {{ LastName ? LastName : 'Not Available' }}

` }) export class AppComponent { LastName : string = null; }
Now, when you run the application it will display the below output in the browser.
Interpolation with Ternary Operator
Method Interpolation in Angular Application:
Let’s see how to create a method using typescript and then we will discuss how to call a class method using interpolation. So, what we will do here is, we will create one method let say GetFullName, and that method will return the full name by combining the first name and last name properties as shown in the below image. Here, you can access the class member using this operator.
Method Interpolation in Angular Application
Once you have a function created in the component, then you can call this function using the interpolation as shown below.
Method Interpolation Example in Angular
So, modify the app.component.ts file as shown below and then see the output.
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
    template: `

Full Name : {{ GetFullName() }}

` }) export class AppComponent { FirstName : string = "Anurag"; LastName : string = "Mohantry"; GetFullName() : string{ return this.FirstName + ' ' + this.LastName; } }
When you run the application, you should get the following output in the browser.
Angular Application Method Interpolation Example
Displaying Images using Angular Interpolation:
It is also possible in angular to display images using Interpolation. Let us say we want to display the image from the below link.

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiF6ZHTcT2879-yeVhYxUE__TH3w59-3uFU1WhKD_NwwdRjZ5bEggrOA_6m0R4FDfMYAXfa2aMFhkZiePHb2bw_r1X752yP3zuCxUTgqwq45lpCAJN_ai4BzjbpNAwzZMam_G6qqde6k5u_/s600/Logo.png

Modify the app.component.ts file as shown below to display images.
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
    template: `
` }) export class AppComponent { ImagePath : string = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiF6ZHTcT2879-yeVhYxUE__TH3w59-3uFU1WhKD_NwwdRjZ5bEggrOA_6m0R4FDfMYAXfa2aMFhkZiePHb2bw_r1X752yP3zuCxUTgqwq45lpCAJN_ai4BzjbpNAwzZMam_G6qqde6k5u_/s600/Logo.png"; }
When you run the application, it will display the following image in the browser.
Displaying Images using Angular Interpolation
In the next article, I am going to discuss the Property Binding in Angular Application. Here, in this article, I try to explain Angular Interpolation with Examples. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this Angular Interpolation with Examples article.

Summary:
I hope this post will be helpful to understand the concept of Angular Interpolation
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Saturday, September 5, 2020

Model Binding in ASP.NET Core

 Admin     September 05, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     1 comment   

In this article, I am going to discuss Model Binding in ASP.NET Core Application. Please read our previous article where we discussed how to create a Form in ASP.NET Core Application using Form Tag Helpers. Please read our previous article as we are going to work with the same application that we worked in our previous article.

What is Model Binding in ASP.NET Core?
The Model Binding is a mechanism in ASP.NET Core Application which extracts the data from an HTTP request and provides them to the controller action method parameters.

The action method parameters may be simple types like integers, strings, etc. or complex types such as Student, Order, Product, etc.

How does the Model Binding works in ASP.NET Core?
As we already discussed, it is our controller action method that is going to handle the incoming HTTP Request in ASP.NET Core MVC Application.

Example using Route Data:
Let us understand this with an example. When we want to view the details of a student whose id is 101, then we generally issue a GET request to the following URL.

http://localhost:52191/home/details/101

Our application default route template ({controller=Home}/{action=Index}/{Id?}) routes the above GET request to the Details(int Id) action method of the HomeController. The following image shows the Details action method of the Home Controller.
Model Binding in ASP.NET Core

So, the value 101 in the request URL is mapped to the Id parameter of the Details(int Id) action method of Home Controller. The MVC Framework will automatically bind the data in the request to the action method parameters by name.

If you notice, the parameter name in the default route template is “Id” and the parameter name of the Details(int Id) action method is also “Id”. So the value 101 in the URL (http://localhost:52191/home/details/101) is mapped to the Id parameter of the Details(int Id) action method.

Example using Query String:
Let us understand this with an example. First, modify the Details Action method as shown below. As you can see we made two changes here. First, we change the return type of the action method to string. Secondly, the Details method now taking two parameters.
How does the Model Binding works in ASP.NET Core

Now issue a Get Request as shown below.

http://localhost:52191/home/details/101?name=dotnet

The above GET request will handle by the Details action method and it will map the value 101 to the Id parameter and the value dotnet will be mapped to the name parameter of the Details action method.

HTTP Request Data Sources:
ASP.NET Core MVC uses three primary data sources to map the HTTP requests data to the action method parameter in the following order:
  1. Form values: Values in the FORM in HTTP POST requests.
  2. Route values: Values provided by the Routing system.
  3. Query string: Values found in the URL’s query string (e.g. after ? character).
Model Binding in ASP.NET Core with Complex Type:
The Model Binding in ASP.NET Core Application also works with complex types like Customer, Student, Order, Product, etc. Let us understand this with an example. In the previous article, we created the following Create Student form.
Model Binding in ASP.NET Core with Complex Type

Add the following Create method to the Home Controller. When the above form is posted, this is the method that is going to handle the request. Please decorate the method with the HttpPost attribute.
[HttpPost]
public ActionResult Create(Student student)
{
    student.StudentId = listStudents.Max(x => x.StudentId) + 1;
    listStudents.Add(student);
    return View("Details", student);
}
How does it work?
When the form is submitted, the values in the form are mapped to the Student object parameter to the Post Create action method. The Model binder in asp.net core application binds the posted form values to the properties of the Student object that is passed as a parameter to the Create() action method.

The value in the input element that has the name attribute set to “Name” is mapped to the Name property of the Studnet object. Similarly, the value in the Branch input element will be mapped to the Branch property of the Student object. This is going to be the same for the rest of the properties like Email and Gender.

Note: At the moment if you navigate to the list view, then you will not find the newly created student data. In a later article, we will discuss how to solve this issue when we are working with the database.

At the moment we don’t have any validation on the Create Student Form. So, if we submit the form without filling any of the form fields, then we will end up creating a new student with empty data.

In the next article, I am going to discuss Model Validation in ASP.NET Core Application. Here, in this article, I try to explain Model Binding in ASP.NET Core Application.

Summary:
I hope this post will be helpful to understand the concept of Model Binding in ASP.NET Core
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Form Tag Helpers in ASP.NET Core

 Admin     September 05, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss the Form Tag Helpers in ASP.NET Core Application. Please read our previous article where we discussed how to create Responsive Navigation Menus in ASP.NET Core Application.

As of now, we have discussed the use of anchor, image, and environment tag helpers in ASP.NET Core Application. This is a continuation part of our previous article. So, please read our previous article before proceeding to this article. Here, in this article, I will discuss how to create a Form in ASP.NET Core Application using the Form Tag Helpers.

What are the Tag Helpers used to create a Form in ASP.NET Core?
In order to create a Form in ASP.NET Core Application, we need to use the following common Tag Helpers.
  1. Form Tag Helper
  2. Input Tag Helper
  3. Label Tag Helper
  4. Textarea Tag Helper
  5. Radio Button Tag Helper
  6. Select Tag Helper
At the end of this article, we will create a Form as shown below using the above Tag Helpers. The following form is used to create a Student.
Form Tag Helpers in ASP.NET Core

Form Tag Helper in ASP.NET Core:
In order to create a Form in ASP.NET Core MVC View, we need to use the <form> tag helper. The syntax to use the Form Tag Helper is shown below.
Form Tag Helper in ASP.NET Core

As you can see in the above image, within the Form Tag Helper, we are using the asp-controller and asp-action tag helpers. These two tag helpers specify the controller and the action method to which the form data is going to be submitted. The method type specifies whether it is a Get request or Post Request. We want to issue a Post request when the form is submitted, so we set the method type as Post.

Note: If you didn’t specify the controller and action name using the asp-controller and asp-action tag helpers, then by default, when the form is submitted, it will be invoked the same action method of the controller which rendered the form.

Input Tag Helper in ASP.NET Core:
The Input Tag Helper in ASP.NET Core binds an HTML <input /> element to a model expression in the razor view. Here, we want a form to create a new Student. So, the model for our view is Student class and we can specify the model using the following directive.
@model Student
In order to capture the student name, we want to display a text box in our form. We also want that text box to bind with the Name property of the Student model class. This can be done very easily by using the asp-for Tag helper as shown below.
<input asp-for=”Name”>
As you can see here we set the value for the asp-for tag helper to the Name property of the Student model class. Here, you will also get the IntelliSense while setting the value property. Later if you change the property name, let say from Name to StudnetName on the Student class, and if you do not change the value assigned to the tag helper, then you will get a compiler error.

The above input tag helper generates an input element with id and name attributes. And both the id and name are set to a value as Name as shown below.
<input type=”text” id=”Name” name=”Name” value=””>
Label Tag Helper in ASP.NET Core:
The Label Tag Helper in ASP.NET Core generates a label with for attribute. The “for” attribute is used to link the label with its corresponding input element. For 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=””>
Here, the label is linked with the input element. This is because both the label for attribute and the input element id attribute has the same value (i.e. Name). That means when we click on the label, then the corresponding input element will receive the focus.

TextArea Tag Helper in ASP.NET Core:
The Textarea tag helper in ASP.NET Core is very much similar to the input tag helper but specifically targets the Textarea element instead of the input element. The textarea tag helper is used by adding the asp-for tag helper attribute to a text area element. For example, let say out Student having a property to store the address, then for address property, we can use textarea tag helper as shown below.
<textarea asp-for=”Address”></textarea>
The text area tag helper was able to generate name and id properties based on the name of the property specified in asp-for. If you want to display the textarea with a specified number of rows and cols, then you need to use the rows and cols attribute as shown below.
<textarea asp-for=”Address” rows=”4″ cols=”30″></textarea>
Select Tag Helper in ASP.NET Core:
The Select Tag helper in ASP.Net Core generates a select tag with its associated option elements. In our example, we want a select element to display the list of Branches. We also want a label that should be linked with the select element. The following code does the same.
<label for="Branch">Branch</label>
<select id="Branch" name="Branch">
    <option value="0">None</option>
    <option value="1">CSE</option>
    <option value="2">ETC</option>
    <option value="3">Mech</option>
</select>
The options for the branch select element can be hard-coded like in the above example, or they can also come from enum or even though from a database table. In our example, we are going to use an enum for the select options.

Radio Button Tag Helper in ASP.NET Core:
The radio button control is designed to support the selection of only one of a mutually exclusive set of predefined options. In order to generate a radio button in the ASP.NET Core application, we need to use the radio button tag helper.

Let us create a Form using the above Form Tag Helpers:
First, add the following Create action method within the Home Controller.
[HttpGet]
public ViewResult Create()
{
    Student student = new Student
    {
        AllGenders = Enum.GetValues(typeof(Gender)).Cast<Gender>().ToList()
    };
    return View(student);
}
Creating the Create View:
Now add a view with the name Create.cshtml within the Home folder of your application. Once you add the Create.cshtml view, then copy and paste the following code in it.
@model FirstCoreMVCApplication.Models.Student
@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<form asp-controller="Home" asp-action="Create" method="post" class="mt-3">
    <div class="form-group row">
        <label asp-for="Name" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="Name" class="form-control" placeholder="Name">
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="Email" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="Email" class="form-control" placeholder="Email">
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="Branch" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <select asp-for="Branch" class="custom-select mr-sm-2"
                    asp-items="Html.GetEnumSelectList<branch>()"></select>
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="Gender" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            @foreach (var gender in Model.AllGenders)
            {
                <label class="radio-inline">
                    <input type="radio" asp-for="Gender" value="@gender" id="Gender@(gender)" />@gender

                </label>
            }
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="Address" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <textarea asp-for="Address" class="form-control" placeholder="Address"></textarea>
        </div>
    </div>
    <div class="form-group row">
        <div class="col-sm-10">
            <button type="submit" class="btn btn-primary">Create</button>
        </div>
    </div>
</form>
Now, run the application and click on the Create Menu and you should see the required view as expected.

In the next article, I am going to discuss Model Binding in ASP.NET Core Application. Here, in this article, I try to explain Form Tag Helpers in ASP.NET Core Application.

Summary:
I hope this post will be helpful to understand the concept of Form Tag Helpers in ASP.NET Core
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Navigation Menus in ASP.NET Core

 Admin     September 05, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss how to create Responsive Navigation Menus in ASP.NET Core Application using bootstrap and JQuery. Please read our previous article, where we discussed the Environment Tag Helper in ASP.NET Core Application.

On a large screen device, we want the navigation menus to look as shown below.
Large Device Navigation Menus in ASP.NET Core Application

On a small screen device, we want to show the navigation menus like below.
Small Device Navigation Menus in ASP.NET Core Application

Adding bootstrap and JQuery files:
The most important point that you need to remember is Bootstrap 4 has a dependency on jQuery. So, here we need to download both bootstraps as well as JQuery into our application. Here, we are going to use a tool called Library Manager (LibMan) to download the required bootstrap and JQuery files. If you are new to Library Manager then I strongly recommended you read the following article where we discussed how to use LibMan to download client-side libraries.

How to Install Bootstrap in ASP.NET Core MVC

Adding images Folder:
Add a folder called images with the wwwroot folder and then paste two different images with the name Logo.png and Student.png.

Adding CSS Folder:
Again add a folder with the name CSS within the wwwroot folder and then add a CSS file with the name MyCustomStyleSheet.css. Once you create the CSS file, then copy and paste the following code in it.
.btn {
   width: 80px;
}
With the above files and folders in place, your wwwroot folder should looks as shown below.
Responsive Navigation Menus in ASP.NET Core Application

_ViewImports.cshtml file:
Please modify the _ViewImports.cshtml file as shown below.
@using FirstCoreMVCApplication.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
_Layout.cshtml file:
Please modify the _Layout.cshtml file as shown below.
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="~/css/MyCustomStyleSheet.css" rel="stylesheet" />
    <link href="~/lib/twitter-bootstrap/css/bootstrap.css" rel="stylesheet" />
    <script src="~/lib/jquery/jquery.js"></script>
    <script src="~/lib/twitter-bootstrap/js/bootstrap.js"></script>
</head>
<body>
    <div class="container">
        <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
            <a class="navbar-brand" asp-controller="home" asp-action="index">
                <img src="~/images/Logo.png" width="30" height="30">
            </a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="collapsibleNavbar">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" asp-controller="home" asp-action="index">List</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" asp-controller="home" asp-action="create">Create</a>
                    </li>
                    <li>
                        <a class="nav-link" asp-controller="home" asp-action="about">About</a>
                    </li>
                    <li>
                        <a class="nav-link" asp-controller="home" asp-action="contact">Contact</a>
                    </li>
                </ul>
            </div>
        </nav>
        <div>
            @RenderBody()
        </div>
    </div>
</body>
</html>
Note: On a small screen device, for the navbar toggle button to work, the jQuery reference must be loaded before loading the Bootstrap JavaScript file. If you change the order, then the navbar toggle button does not work as expected.

Creating Models:
First, we need to create two enums to store the Gender and Branch of a student. So, create two models within the Models folder with the name Gender and Branch and then copy and paste the following code.

Branch.cs
namespace FirstCoreMVCApplication.Models
{
    public enum Branch
    {
        None,
        CSE,
        ETC,
        Mech
    }
}
Gender.cs
namespace FirstCoreMVCApplication.Models
{
    public enum Gender
    {
        Male,
        Female
    }
}
Please add the following Student model with the Models folder.

Student.cs
using System.Collections.Generic;
namespace FirstCoreMVCApplication.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public Branch Branch { get; set; }
        public Gender Gender { get; set; }
        public string Address { get; set; }
        public IEnumerable<Gender> AllGenders { set; get; }
    }
}
Modifying the Home Controller:
Please modify the Home Controller as shown below.
using FirstCoreMVCApplication.Models;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        private List<Student> listStudents = new List<Student>();
        public HomeController()
        {
            listStudents = new List<Student>()
            {
               new Student() { StudentId = 101, Name = "James", Branch = Branch.CSE, Gender = Gender.Male, Address = "A1-2018", Email = "James@g.com" },
               new Student() { StudentId = 102, Name = "Priyanka", Branch = Branch.ETC, Gender = Gender.Female, Address = "A1-2019", Email = "Priyanka@g.com" },
               new Student() { StudentId = 103, Name = "David", Branch = Branch.CSE, Gender = Gender.Male, Address = "A1-2020", Email = "David@g.com" }
            };
        }
        public ViewResult Index()
        {
            return View(listStudents);
        }
        public ViewResult Details(int Id)
        {
            var studentDetails = listStudents.FirstOrDefault(std => std.StudentId == Id);
            return View(studentDetails);
        }
    }
}
Index.cshtml file:
Please modify the Index view as shown below.
@model List<Student>
@{
    ViewBag.Title = "Student List";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="card-deck">
    @foreach (var student in Model)
    {
        <div class="card m-3">
            <div class="card-header">
                <h3>@student.Name</h3>
            </div>
            <img class="card-img-top" src="~/images/Student.png" />
            <div class="card-footer text-center">
                <div class="card-footer text-center">
                    <a asp-controller="home" asp-action="details"
                       asp-route-id="@student.StudentId" class="btn btn-primary m-1">View</a>
                    <a href="#" class="btn btn-primary m-1">Edit</a>
                    <a href="#" class="btn btn-danger m-1">Delete</a>
                </div>
            </div>
        </div>
    }
</div>
Detail.cshtml file:
Please modify the Details view as shown below.
@model Student
@{
    ViewBag.Title = "Student Details";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row justify-content-center m-3">
    <div class="col-sm-8">
        <div class="card">
            <div class="card-header">
                <h1>@Model.Name</h1>
            </div>
            <div class="card-body text-center">
                <img class="card-img-top" src="~/images/Student.png" />
                <h4>Studnet ID : @Model.StudentId</h4>
                <h4>Email : @Model.Email</h4>
                <h4>Branch : @Model.Branch</h4>
                <h4>Gender : @Model.Gender</h4>
                <h4>Address : @Model.Address</h4>
            </div>
            <div class="card-footer text-center">
                <a href="#" class="btn btn-primary">Back</a>
                <a href="#" class="btn btn-primary">Edit</a>
                <a href="#" class="btn btn-danger">Delete</a>
            </div>
        </div>
    </div>
</div>
Now run the application and see the navigation menus which should be responsive. In the next article, I am going to discuss Form Tag Helpers in ASP.NET Core Application. Here, in this article, I try to explain how to create Responsive Navigation Menus in ASP.NET Core Application using bootstrap with some examples.

Summary:
I hope this post will be helpful to understand the concept of Navigation Menus in ASP.NET Core
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Environment Tag Helper in ASP.NET Core

 Admin     September 05, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss the Environment Tag Helper in ASP.NET Core Application with some examples. Please read our previous article, where we discussed the Image Tag Helper in ASP.NET Core Application with an example. As part of this article, we are going to discuss the following pointers.
1. Different Environments in Software Development
        Development Environment
        Staging Environment
        Production Environment
2. Understanding the use of Environment Tag Helper in ASP.NET Core
3. How to set Environment in ASP.NET Core Application?
4. What is the use of integrity in CDN Link?
5. What if the CDN is down?
6. Multiple Examples to understand the ASP.NET Core Environment Tag Helper
Different Environments in Software Development:
Nowadays, most of the software development organizations typically have the following three development environments.
  1. Development Environment
  2. Staging Environment
  3. Production Environment
Development Environment:
As a software developer, for our day to day development work, we generally use this development environment. In this environment, we generally use the non-minified JavaScript and CSS files for the purpose of easy debugging. Another use of this environment is that we want to show the developer exception page if there is an unhandled exception so that we can understand the root cause of the exception and then take necessary action to fix the issue.

Staging Environment:
The staging environment is very much similar to the production environment. Nowadays, many organizations use this staging environment to identify any deployment-related issues. Again, if you are developing a B2B (Business to Business) application, then you may be using services provided by other service providers. So, many organizations set up their staging environment to check the service providers as well for complete end to end testing.

In the staging environment, we usually do not perform the debugging and troubleshoot, so to get a better performance we use minified JavaScript and CSS files. Again, if there is an exception, instead of showing the developer exception page, we need to show a friendly error page. The friendly error page will not contain any technical exception details instead it shows a generic error message like below.
“Something went wrong, our IT team working on this to solve as soon as possible. If you need further details then please email, chat or call our support team using the below contact details”
Production Environment:
This is the actual live environment that is used for day to day business. The Production environment should be configured for maximum security as well as maximum performance. So, in this environment, we need to use the minified JavaScript and CSS files. For better security, we need to show a User-Friendly Error Page instead of the Developer Exception Page when there is an exception.

Understanding the use of Environment Tag Helper in ASP.NET Core:
In our Application, we are using bootstrap. For ease of debugging, i.e. on our local development (i.e. on Development Environment) we want to load the non-minified bootstrap CSS file (bootstrap.css).

On the Staging and Production or any other environment except the Development environment, we want to load the minified bootstrap CSS file (bootstrap.min.css) from a CDN (Content Delivery Network) for better performance.

However, if the CDN is down or for some reason, our application is not able to load the file from CDN then we want our application to fallback and load the minified bootstrap file (bootstrap.min.css) from our own server.

We can achieve this very easily by using the Environment Tag Helper in ASP.NET Core Application. But before understanding how to use the Environment Tag Helper, let us first understand how we set the environment (i.e. Development, Staging, and Production) in ASP.NET Core.

How to set Environment in ASP.NET Core Application?
In order to set the Application Environment (i.e. Development, Staging, or Production) we need to use the ASPNETCORE_ENVIRONMENT variable. We can set this in the launchsettings.json file. You can find the launchsettings.json file within the properties. Open the launchsettings.json file and set the environment as Development as shown in the below image.
How to set Environment in ASP.NET Core Application?

Note: The other possible values for the ASPNETCORE_ENVIRONMENT variable are Staging and Production. It is also possible to create our own environment that we will discuss in our upcoming article.

Installing bootstrap:
Please install bootstrap with the wwwroot folder. Please read the following article where we discussed how to install bootstrap in ASP.NET Core Application.

How to Install Bootstrap in ASP.NET Core MVC

Modifying the _ViewImports.cshtml file:
Please modify the _ViewImports.cshtml file as shown below to include the tag helpers into our application globally.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
ASP.NET Core Environment Tag Helper with Examples:
The Environment Tag Helper in ASP.NET Core supports rendering different content based on the environment of the application. The environment of the application is set by using the ASPNETCORE_ENVIRONMENT variable within the launchsettings.json file that we already discussed.

Example: If you want to load the non-minified bootstrap CSS files from your own server when the application environment is Development, then you need to set the environment tag helper as shown below.
ASP.NET Core Environment Tag Helper

Example:
If you want to load the minified bootstrap CSS files from the CDN (Content Delivery Network) when the application environment is Staging or Production, then you need to set the environment tag helper as shown below.
ASP.NET Core Environment Tag Helper Staging and Production

In order to get the bootstrap CDN link, please visit the following URL.

https://getbootstrap.com/

Once you visit the above URL then copy the CDN link as shown below.
bootstrap CSS files from the CDN (Content Delivery Network)

Using the include attribute of the environment tag helper we can set a single hosting environment name or a comma-separated list of hosting environment names. Along with the include attribute, we can also use the exclude attribute.

The exclude attribute is basically used to render the content of the environment tag when the hosting environment does not match the environment specified in the exclude the attribute. The following example loads the minified CSS file from the CDN when the application environment is not Development.
Environment Tag Helper in ASP.NET Core

What is the use of integrity in CDN Link?
The integrity attribute on the element is used for Subresource Integrity (SRI) check. The SRI is a security feature that allows a browser to check if the file is retrieved from the CDN has been maliciously altered. When the browser downloads the file, it regenerates the hash and compares the regenerate the hash value against the integrity attribute hash value. If both the hash values match, then only the browser allows the file to be downloaded otherwise it is blocked.

What if the CDN is down?
If the CDN is down or for some reason, our application is not able to reach the CDN, then we want our application to fall back and load the minified bootstrap file (bootstrap.min.css) from our own server. Please have a look at the following image.
What if the CDN is down

Explanation of the above Code:
If the environment is “Development”, then we are loading the non-minified bootstrap CSS file (i.e. bootstrap.css) from our own server. On the other hand, if the application environment is other than “Development”, then we are trying the load the minified bootstrap CSS file (i.e. bootstrap.min.css) from the CDN.

Along the same line, we also specified a fallback source using the asp-fallback-href attribute. This attribute is basically used when the CDN is down or for some reason if our application is unable to reach the CDN. In that case, our application falls back and download the minified bootstrap file (i.e. bootstrap.min.css) from our own server.

In order to check whether the CDN is down, we are using the following 3 attributes and their associated values.
  1. asp-fallback-test-class=”sr-only”
  2. asp-fallback-test-property=”position”
  3. asp-fallback-test-value=”absolute”
Let us understand all the above with an example.

Modifying the _Layout.cshtml file:
Please modify the _Layout.cshtml file as shown below. Here, we are loading the bootstrap.css files based on the application environment. We also specify the falls back path in case if the environment is other than Development and the CDN is down.
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
   
    <environment include="Development">
        <link href="~/lib/twitter-bootstrap/css/bootstrap.css" rel="stylesheet" />
    </environment>
    <environment exclude="Development">
        <link rel="stylesheet"
              integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
              crossorigin="anonymous"
              href="https://sstackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
              asp-fallback-href="~/lib/twitter-bootstrap/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position"
              asp-fallback-test-value="absolute"
              asp-suppress-fallback-integrity="true" />
    </environment>
</head>
<body>
    <div class="container">
        @RenderBody()
    </div>
</body>
</html>
Modify the Home Controller:
Please modify the Home Controller as shown below.
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }
    }
}
Modify the Index.cshtml file as shown below.
@{
    ViewBag.Title = "Index";
     Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Index View</h1>
Now run the application and view the page source code.
Setting Environment as Development using Environment Tag Helper

As you can see in the above image, the boostrap.css file is load from our own server and this makes sense because currently, we set the application environment as Development. Let us change the environment to Staging and see whether it load the file from CDN or not.

Modify the Environment as Staging:
Open the launchsettings.json file and modify the ASPNETCORE_ENVIRONMENT variable value to staging as shown below.
Setting Environment to Staging in ASP.NET Core

With the above changes in place, now run the application and view the source, which should show the bootsrap.css file being downloaded from the CDN as shown below.
Using CDN in ASP.NET Core

Let intentionally change the integrity value of the CDN to make sure if the CDN fails whether it load the minified bootstrap.css file from our local server or not. So, add some random value to the value of the integrity attribute of the CDN link. And then load the page and view the page source code. Now, in order to check this open the browser developer tools by pressing the F12 key and then click on the Network tab as shown below.
Setting Fall back URL using Environment Tag Helper in ASP.NET Core

As you can see in the above image, first it tries to load the bootstrap.css file from CDN and it fails as the integrity value is not matched. Then it loads the file from its own application server.

In the next article, I am going to discuss the Bootstrap Navigation Menu in ASP.NET Core MVC Application. Here, in this article, I try to explain Environment Tag Helper in ASP.NET Core Application with some examples.

Summary:
I hope this post will be helpful to understand the concept of Environment Tag Helper in ASP.NET Core
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Image Tag Helper in ASP.NET Core

 Admin     September 05, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss the Image Tag Helper in ASP.NET Core MVC Application with some examples. Please read our previous article, where we discussed the basics of Tag Helpers in ASP.NET Core MVC Application. As part of this article, we are going to discuss the following pointers. As part of this article, we are going to discuss the following pointers.
  1. Understanding the Browser Cache
  2. How to Disable Browser Cache?
  3. Why we need Image Tag Helper in ASP.NET Core?
  4. How to use Image Tag Helper in ASP.NET Core?
  5. Understanding ASP.NET Core Image Tag Helper with an example
  6. How Does the Image Tag Helper work in ASP.NET Core?
Understanding the Browser Cache:
In general, when you visit a web page and if that web page contains some image, then most of the modern web browser cache the images for later use. In the future, when you revisit that web page, then the browser loads the images from the cache instead of downloading the images from the server. In most of the caches, this is not an issue as the images are not changes that often for a web page.

How to Disable Browser Cache?
If you want then you can also disable the browser cache. Once you disable the browser cache then it will not cache the images and each and every time it will download the images from the server when you visit the page. In order to disable browser cache in Google Chrome, you need to follow the below steps.

Press the F12 key to launch the Browser Developer Tools. Then click on the “Network” tab and finally, check then “Disable Cache” checkbox as shown in the below image.
How to Disable Browser Cache

Why we need Image Tag Helper in ASP.NET Core?
If you disable the browser cache, then each and every time it will download the image from the server. If you didn’t disable the browser cache, then it will serve the image from the browser cache. But the problem with this approach is that, if you changed the image, then you will not get the updated image.

To overcome the above problems, i.e. download the image from the server only when it has changed else serve the image from the browser cache, we need to use the Image Tag helper in ASP.NET Core MVC Application.

How to use Image Tag Helper in ASP.NET Core?
In order to use the Image Tag Helper in ASP.NET Core Application, you need to add the asp-append-version attribute to the <img> tag and need to set the value to true as shown below.
How to use Image Tag Helper in ASP.NET Core

Understanding ASP.NET Core Image Tag Helper with an example:
First, create a folder with the name images within the wwwroot folder. Once you create the images folder, add two images with the name Image1.jpg and Image2.jpg. For better understanding add two different images.

Modify the Home Controller as shown below.
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }
    }
}
Modify the Index View as shown below.
@{
    ViewBag.Title = "Index";
    Layout = null;
}
<img src="~/images/Image1.jpg" asp-append-version="true" />
Modify the _ViewImports.cshtml file as shown below.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
With the above changes in place, now run the application and view the page source code. Once you view the page source code, you will find the following code for the image tag.
How Does the Image Tag Helper work in ASP.NET Core

How Does the Image Tag Helper work in ASP.NET Core?
The ASP.NET Core Image Tag Helper enhances the tag to provide cache-busting behavior for the static image files. That means based on the content of the image, a unique hash value is calculated and then appended to the image URL as you can see in the above image. This unique hash value decides whether to load the image from the server or to load the image from the browser cache. If the hash value changes then it will reload the image from the server else it will reload the image from the cache.

Now reload the page multiple times and you will see the hash is not going to change and hence it will load the image from the browser cache.

Now, rename Image1 as Image3 and Image2 as Image1 within the images folder and reload the page and you will see a different hash value as well as the updated image which proofs that it loads the image from the server.

In the next article, I am going to discuss the Environment Tag Helper in ASP.NET Core MVC Application. Here, in this article, I try to explain Image Tag Helper in ASP.NET Core MVC Application with some examples. I hope you enjoy this article.

Summary:
I hope this post will be helpful to understand the concept of Image Tag Helper in ASP.NET Core
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Tag Helpers in ASP.NET Core MVC

 Admin     September 05, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss Tag Helpers in ASP.NET Core MVC Application with some examples. Tag helpers are one of the new features introduced in ASP.NET Core MVC. Please read our previous article, where we discussed how to use bootstrap in ASP.NET Core MVC Application. As part of this article, we are going to discuss the following pointers.
  1. What are Tag Helpers in ASP.NET Core?
  2. Types of Tag Helpers
  3. How to use built-in Tag Helpers in ASP.NET Core MVC?
  4. Understanding the Anchor Tag Helper in ASP.NET Core
  5. Advantage of using Tag helpers in ASP.NET Core MVC Application
What are Tag Helpers in ASP.NET Core?
Tag Helpers in ASP.NET Core are the server-side components. They are basically used to perform defined transformations on HTML Elements. As they are server-side components, so they are going to be processed on the server to create and render HTML elements in the Razor files.

If you are coming from an ASP.NET MVC background, then you may be worked with the HTML helpers. The Tag Helpers are similar to the HTML helpers.

Types of Tag Helpers in ASP.NET Core:
There are two types of Tag helpers in ASP.NET Core. They are as follows:
  1. Built-In Tag Helpers: They come in-built in the ASP.NET Core Framework and can perform common tasks like generating links, creating forms, loading assets, showing validation messages, etc.
  2. Custom Tag Helper: That can be created by us to perform our desired transformation on an HTML element.
Note: In this article, I am going to discuss the Built-in Tag Helpers and in our upcoming articles, I will discuss the Custom Tag Helpers.

Please read the following articles before proceeding to this article as we are going to use layout, ViewImport, and bootstrap in this demo.

How to create and use Layout in ASP.NET Core?
Understanding the need and use of _ViewImport.cshtml file.
How to install bootstrap in ASP.NET Core?
Using Bootstrap in ASP.NET Core.


How to use built-in Tag Helpers in ASP.NET Core MVC?
In order to make the built-in tag helpers available for all the views of our application, import the tag helpers using the _ViewImports.cshtml file. You need to import them using the @addTagHelper directive as shown below.

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

The @addTagHelper makes the built-in tag helpers to available in the application which are defined in an assembly called Microsoft.AspNetCore.Mvc.TagHelpers. Here the wildcard “*” specifies that all the Tag Helpers are made available.

Generating Links using Tag Helpers in ASP.NET Core MVC Application:
Let us understand this with an example. First, create a class file with the name Student.cs within the Models folder. Once you create the Student.cs class file, then copy and paste the following code in it.
namespace FirstCoreMVCApplication.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string Branch { get; set; }
        public string Section { get; set; }
        public string Gender { get; set; }
    }
}
Modifying Home Controller:
Modify the Home Controller as shown below. Here we have created two action methods. To make the things simple and to keep the focus on Tag helpers, here we have hardcode the required student data within the action method.
using FirstCoreMVCApplication.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            List<Student> listStudents = new List<Student>()
            {
               new Student() { StudentId = 101, Name = "James", Branch = "CSE", Section = "A", Gender = "Male" },
               new Student() { StudentId = 102, Name = "Smith", Branch = "ETC", Section = "B", Gender = "Male" },
               new Student() { StudentId = 103, Name = "David", Branch = "CSE", Section = "A", Gender = "Male" },
               new Student() { StudentId = 104, Name = "Sara", Branch = "CSE", Section = "A", Gender = "Female" },
               new Student() { StudentId = 105, Name = "Pam", Branch = "ETC", Section = "B", Gender = "Female" }
            };
            return View(listStudents);
        }
        public ViewResult Details(int Id)
        {
            var studentDetails = new Student() { StudentId = Id, Name = "James", Branch = "CSE", Section = "A", Gender = "Male" };
            return View(studentDetails);
        }
    }
}
Creating the Details view:
Details.cshtml:
@model FirstCoreMVCApplication.Models.Student
@{
    ViewBag.Title = "Student Details";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row justify-content-center m-3">
    <div class="col-sm-8">
        <div class="card">
            <div class="card-header text-center">
                <h1>@Model.Name</h1>
            </div>
            <div class="card-body text-center">
                <h4>Studnet ID : @Model.StudentId</h4>
                <h4>Branch : @Model.Branch</h4>
                <h4>Section : @Model.Section</h4>
                <h4>Gender : @Model.Gender</h4>
            </div>
            <div class="card-footer text-center">
                <a href="#" class="btn btn-primary">Back</a>
            </div>
        </div>
    </div>
</div>
Index View: Now in the index view, we have to provide the View button as a link and on the click, on the View button, we need to display the Student Details. For example, we need to generate the following hyperlink. The number 101 is the ID of the student whose details we want to view.

/home/details/101

We have many different options to generate a link in ASP.NET Core MVC Application. Let us discuss all the possible options to generate a link and then we will discuss why we should use Tag Helper over others.

Option1: Manually generating the links:
@model List<FirstCoreMVCApplication.Models.Student>
@{
    ViewBag.Title = "Student List";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="table-responsive">
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>View</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var student in Model)
            {
                <tr>
                    <td>@student.StudentId</td>
                    <td>@student.Name</td>
                    <td class="text-center">View</td>
                </tr>
            }
        </tbody>
    </table>
</div>
Option2: Using HTML helpers
Tag Helpers in ASP.NET Core MVC

Option3: Using Tag Helpers:
In order to use Tag Helpers first import the @addTagHelper directive in the _ViewImport.cshtml file. Along with the @addTagHelper directive, we also add the model namespace using the @using directive. So, modify the _ViewImport.cshtml file as shown below which you can find within the Views folder.
@using FirstCoreMVCApplication.Models;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Then modify the Index view as shown below.
@model List<Student>
@{
    ViewBag.Title = "Student List";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="table-responsive">
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>View</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var student in Model)
            {
                <tr>
                    <td>@student.StudentId</td>
                    <td>@student.Name</td>
                    <td>
                        <a asp-controller="Home" asp-action="Details"
                           asp-route-id="@student.StudentId">View</a>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>
Now run the application and it should work as expected.

Understanding the Anchor Tag Helper in ASP.NET Core:
The Anchor Tag Helper in ASP.NET Core creates the standard HTML anchor (<a … ></a>) tag by adding new attributes such as:
  1. asp-controller: It is used to specify the controller to target based on the routing system. If you omitted this, then the controller of the current view is used by default.
  2. asp-action: It is used to specify the Action method to target based on the routing system. If you omitted this attribute then the action rendering the current view is used by default.
  3. asp-route-{value}: It is used for specifying the additional segment value for the URL. For example, asp-route-id is used to provide value for the ‘id’ segment.
The rendered anchor element’s “href” attribute value is determined by the values of these “asp-“ attributes. As the name says, the asp-controller specifies the name of the controller whereas asp-action specifies the name of the action name. Similarly, the asp-route-{value} attribute is used to include route data in the generated href attribute value. {value} can be replaced with route parameters such as id, name, etc.

Let us have a look at the following image.
Understanding the Anchor Tag Helper in ASP.NET Core MVC

As you can see in the above image, manually generating the links is much easier than using HTML Helpers or Tag Helpers. Then why should we use HTML helpers or Tag Helpers over manually generating these links in ASP.NET Core?

Advantage of using Tag helpers in ASP.NET Core MVC Application:
In ASP.NET Core MVC, the Tag Helpers generates links based on the application routing templates. That means. in the future, if we change routing templates, then the link generated by tag helpers will automatically reflect those changes made to the routing templates. So, the generated links just work as expected without any trouble.

On the other hand, if we have hard-coded the URL paths manually, then we need to change the code wherever we have hardcoded the path in our application when the application routing templates change.

Let’s understand this with an example
The following is the Startup class of our application. Please modify the Startup class as shown below.
Tag Helpers in ASP.NET Core MVC Application with Examples

As you can see in the above image, we have the route template pattern as {controller=Home}/{action=Index}/{id?}.

Generating Link Manually:
In the following code, we are manually generating the link by hard-coding the URL paths as /Home/Details.
View
Generating Link using Tag Helper:
In the following code, we are generating the link using an anchor tag helper.
View
As you can see with Tag Helper, we have not hardcoded the URL paths. Here, we are only specifying the controller and action names and the route parameters along with their values. When the tag helpers are executed on the server they look at the route templates and generate the correct URLs automatically.

Here, in both the techniques generate the same URL path i.e. (/Home/Details/101) and it also works with the current route template i.e. ({controller=Home}/{action=Index}/{id?})

Now let us change the routing template as shown below. Notice here in the route template, we have added the string literal “dotnet”.
Tag Helpers in ASP.NET Core MVC Application

With the above changes in place, now if you generate the link manually, then it will not work whereas if you generate the link with Tag Helpers then it will work as expected.

We also have tag helpers in ASP.NET Core to generate forms. When the form is posted back to the server, the posted form values are automatically handled and the associated validation messages are displayed. Without these tag helpers, we would have to write a lot of custom code to achieve the same. If this is not clear at the moment then don’t worry we will discuss this with examples in our upcoming articles.

That’s it for today. In the next article, I am going to discuss the Image Tag Helper in ASP.NET Core MVC Application. Here, in this article, I try to explain the basics of Tag Helpers in ASP.NET Core MVC Application with some examples. I hope you enjoy this article.

Summary:
I hope this post will be helpful to understand the concept of Tag Helpers in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Older Posts

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • ASP.NET State Management
    State management is a technique or way to maintain / store the state of an Asp.Net controls, web page information, object/data, and user in ...
  • HTTP Client Message Handler in Web API
    In this article, I am going to discuss HTTP Client Message Handler in Web API with real-time examples. As we already discussed in HTTP Mes...
  • ASP.NET Web API Basic Authentication
    In this article, I am going to discuss how to implement the ASP.NET Web API Basic Authentication step by step with an example. Please read...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Anonymous Types in C#
    Hi friends! Today we are going to learn about Anonymous Types in C#. Let's start with the Introduction Anonymous is a type that does...
  • Development Approach with Entity Framework
    In this article, I will discuss Development Approach with Entity Framework . The entity framework provides three different approaches when ...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape