Using a tag helper to add a “read more” in asp.net core

How to add a tag helper for a “read more” link in asp.net core

If you use a “read more” link frequently, it is worthwhile to create a tag helper to automate this system.

Here is how we want to set up our code:

<p>My Introductory paragraph </p>
<read-more story=”mystory”></read-more>

<story-continue story=”mystory”>
<p> My following paragraphs</p>
</story-continue>

This should result in:

<p>My Introductory paragraph </p>
<a id = “mystory”  href=”#mystoryContent” data-toggle =”collapse” >Read More</a>

<div class=”collapse” id=”mystoryContent” name=”mystoryContent” ></div>
<p> My following paragraphs</p>

This example is using  the Bootstrap collapse function and requires Bootstrap be included on your webpage.

The tag helpers

Here is the readmore taghelper.

namespace example.TagHelpers
{

[HtmlTargetElement(“read-more”)]
public class ReadMoreTagHelper : TagHelper
{
public string Story { get; set; }

public override void Process(TagHelperContext context,      TagHelperOutput output)
{
output.TagName = “a”;
output.Attributes.SetAttribute(“id”, “link” + Story);
output.Attributes.SetAttribute(“href”, “#” + Story + “Content”);
output.Attributes.SetAttribute(“data-toggle”, “collapse”);
output.Content.SetContent(“Read More.”);
}
}

}

Add at the top:
using Microsoft.AspNetCore.Razor.TagHelpers;

Save in a file ReadMoreTagHelper.cs in a new TagHelpers folder.

Now add the StoryContinue tag helper file.

namespace example.TagHelpers
{
[HtmlTargetElement(“story-continue”)]
public class StoryContinueTagHelper : TagHelper
{
public string Story { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = “div”;
output.Attributes.SetAttribute(“class”, “collapse”);
output.Attributes.SetAttribute(“id”, Story + “Content”);
output.Attributes.SetAttribute(“name”, Story + “Content”);

}

Add at the top:
using Microsoft.AspNetCore.Razor.TagHelpers;

Save in a file StoryContinueTagHelper.cs in the TagHelpers folder.

More Options

Using this tag helper, you will get easy to reuse “read more”  code. Just change the ” story=” to a different identifier for each story. You can add many other attributes to the link and to the div. For example, add a class to your link to format it. Add an attribute “aria-controls”  to  make your site more accessible.  Add an “onClick”  to perform additional  on click  work such as allowing Google Analytics to count how many times the  “read more” link was clicked. The more attributes you add, the more time you are saving by setting up the Tag Helper just once.

You would also want to write javascript to change the “Read More” text to “Read Less” when the link is clicked.

Leave a Reply

Your email address will not be published. Required fields are marked *