Click here to Skip to main content
15,748,930 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

String is displayed on the website in < p >
string = "long text $word long text";

I want every substring starting with $ to be clickable link:

<a asp-action="Index" asp-controller="Search" asp-route-query="@match">@match</a>

Solution looks simple, just inject code above into string, and display it as Html.Raw

foreach (Match match in Regex.Matches(text, @"($\w+)"))
                text = text.Replace(match.Value, $"<a asp-action=\"Index\" asp-controller=\"Search\" asp-route-query=\"{match.Value}\">{match.Value}</a>");

            return text;

This is probably the best solution. Except it doesn't work. Text is displayed on the website, injected code is visible in HTML, but "link" is not clickable.

Any ideas how to fix it?

What I have tried:

Obviously googling and some tinkering around but this is what I have and it doesn't work.
Updated 28-Apr-21 22:01pm
Gerry Schmitz 30-Mar-21 14:10pm    
I think you should be showing the "injected HTML".

1 solution

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>";
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900