ASP.NET Core 2: TagHelpers Part 1

images.jpgTagHelpers let you simplify the markup in your Razor pages and improve readability.

Which would you rather have on your Razor Page?

<email-support></email-support>

or

taghelper1.png

Step 1: Create a new ASP.NET Core project, any template will do. Call it TagThis

Step 2: Add a class called EmailSupport.cs to the web project

This class tells ASP.NET Core how to render the custom tag and is fairly self-explanatory in this basic example

public class EmailSupport :TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        //The Html Tag will be an Anchor
        output.TagName = "a";
 
        //Add the link and css class to the anchor tag
        output.Attributes.Add(new TagHelperAttribute("href","mailto:Support@IanVink.com"));
        output.Attributes.Add(new TagHelperAttribute("class""btn btn-primary"));
 
        //Add text to the link
        output.Content.SetHtmlContent("Email Support");
    }
}

Step 3: Edit the _ViewImports.cshtml file and tell it to add all Tag Helpers from the TagThis assembly. Notice the “*”

@addTagHelper *, TagThis

Step 4: Add Bootstrap and FontAwesome css to your _Layout.cshtml to make it look pretty

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" >
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

Step 5: Add this markup to a page.

Warning: Your TagHelper class, if its name has CaSe, must be referenced in lowercase with a ‘-‘ separating the words. For example, EmailSupport becomes <email-support>.

<email-support></email-support>

 


The result:

taghelperemail.png

Beautiful button, beautiful markup

Advertisements

2 thoughts on “ASP.NET Core 2: TagHelpers Part 1

  1. Pingback: ASP.Net Core 2: TagHelper Part 2: Display downloaded Quotes | Xamarin and Visual Studio for Beginners

  2. Pingback: ASP.Net Core 2: TagHelper Part 3: Custom html attributes | Xamarin and Visual Studio for Beginners

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s