The
asp-action
and
asp-controller
attributes are tag helpers:
ASP.NET Core built-in Tag Helpers | Microsoft Docs[
^]
In a Razor file, these are processed on the server to generate a link with an
href
attribute.
When you inject a string as raw HTML, no tag helpers will be processed. Your HTML will contain the
asp-
attributes, which are not understood by the browser. It will not contain an
href
attribute, so it will not be clickable.
The simple solution is to generate the URL yourself, using the
IUrlHelper
.
You should also take care to HTML-encode the matches to avoid cross-site scripting.
And instead of replacing each match in turn, use a match evaluator:
MatchEvaluator Delegate (System.Text.RegularExpressions) | Microsoft Docs[
^]
text = Regex.Replace(text, @"($\w+)", match =>
{
string url = Url.Action("Index", "Search", new { query = match.Value });
string text = HttpUtility.HtmlEncode(match.Value);
return $"<a href=\"{url}\">{text}</a>";
});