What is a tag helper?
A tag helper is a shortcut for generating html tags such as
A tag helper looks like any html tag but has additional attributes that start with
asp-. These attributes are interpreted on the server side to generate the correct html tags.
Any html attributes like
class, etc., can be applied to tag helpers. They can be understood by web designers, who can modify them as per their expertise.
Tag helpers are the preferred way in razor pages.
Important: Tag helpers are not enabled by default
A razor page must include
@addTagHelper directive to enable tag helpers. Tag helpers are usually included through a common _ViewImports file.
The following razor page is enabled for tag helpers.
// any razor page, say, index.cshtml // NOTE: this must be PASTED as such @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
How many Tag Helpers are there?
ASP.NET Core provides some common ones, but you can add your own also.
The most common ones can be seen here Built-in ASP.NET Core Tag Helpers
We recommend learning them at the point of use. A brief introduction can be seen in the above MSDN page for general knowledge.
About the anchor tag helper
An anchor tag helper is used to generate the standard anchor link.
The most common attribute
asp-page specifies the name of the page to navigate to.[see an example in the walkthrough next]
Another most common attribute
asp-page-handler specifies the name of the event handler that handles the click event. [we shall cover it later, but you can see an example here (C# ASP.NET Core) Deleting Records from a Database with EF Core]
asp-area specifies the name of the area folder [we shall cover it later, but you can see (C# ASP.NET Core) Concept of Areas and an Authorization Scheme].
The less common attributes
asp-protocol, asp-host specify the fragments of a URL.
Walkthrough on anchor tag helpers
We shall now have a walkthrough where we shall have two razor pages, each containing an anchor link for navigating to the other page.
Create a simple ASP.NET Core project and add two razor pages called "Index" and "Login" so that both of them live side-by-side in the same "Pages" folder.
Complete the Index page as follows:
@page // enable tag helpers @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers <h1>Index Page</h1> // the asp-page attribute specifies the // name of the page to navigate to <a asp-page="Login">Login</a>
Complete the Login page as follows:
@page // enable tag helpers @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers <h1>Login Page</h1> // the asp-page attribute specifies the // name of the page to navigate to <a asp-page="Index">back to home</a>
Run the project to verify that the navigation works!
This Blog Post/Article "(C# ASP.NET Core) Inter Page Navigation and Linking of Razor Pages with Anchor Tag Helpers" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.