Retrieve Page Tags in XbK

Let’s assume you developed a widget using Xperience by Kentico (XbK) that allows you to display various pages and you need to display their associated taxonomy (Tags).

Assuming your page content type has a field called Tags as taxonomy data type, you can easily display the taxonomy GUID stored in the page Tag field using the following code in the View:

@foreach (var pageItem in Model) 
{ 
  <h1>@tag.PageTitle</h1>
  <p>@tag.PageDescription</p>
  @foreach (var tag in pageItem.Tags) {
    <p>Tags: @tag.Identifier</p>
  } 
}

All good, but because the TagReference class only allows Identifier property you need to find a way to display the actual taxonomy field Title associated with the Tag GUID.

First, make sure you inject the ITaxonomyRetriever at the top of the View.

@inject ITaxonomyRetriever taxonomyRetriever;

Next, use the ITaxonomyRetriever to retrieve the page taxonomy and its tags which will include all of the tag fields (ID, Title, Name).

@foreach (var pageItem in Model) 
{ 
  <h1>@tag.PageTitle</h1>
  <p>@tag.PageDescription</p>
  @foreach (var tag in pageItem.Tags) {
    var pageTag = await taxonomyRetriever.RetrieveTags([tag.Identifier], "en");
    var myTagID = pageTag.Select(t => t.ID).FirstOrDefault(); // Tag ID
    var myTagTitle = pageTag.Select(t => t.Title).FirstOrDefault(); // Tag Title
    <p>Tags: <a href="/Tags?tag=@myTagID">@myTagTitle</a></p>
  } 
}

Update!

As you noticed in the previous example, the logic of retrieving the tags was done in the Razor page. It works but it is not the best practice in ASP.NET Core development, often referred to as the separation of concerns.
So, moving the logic out of the Razor view and into the View Component is a must. This makes the code more maintainable, testable, and readable.

On your View Component, make sure you inject the ITaxonomyRetriever:

private readonly ITaxonomyRetriever taxonomyRetriever;

public YourViewComponent(ITaxonomyRetriever taxonomyRetriever)
{
    this.taxonomyRetriever = taxonomyRetriever;
}

Next, apply the magic process of retrieving the tags:

// --- Start Tag Retrieval ---
var tags = new List<Tag>();
IEnumerable<TagReference> pageTags = (page.Tags as IEnumerable<TagReference>) ?? Enumerable.Empty<TagReference>();

var tagIdentifiers = pageTags.Select(t => t.Identifier).ToList();
if (tagIdentifiers.Any())
{
 var retrievedTags = await taxonomyRetriever.RetrieveTags(tagIdentifiers.ToArray(), "en");
 tags.AddRange(retrievedTags);
}
// --- End Tag Retrieval ---

And now display the tags on your Razor page:

@foreach (var tag in Model.Tags)
{
    <a href="/Tags?tag=@tag.ID">@tag.Title</a>
}

References:
Retrieve information about tags and taxonomies
Kentico Community Portal
Class TagReference