Click here to Skip to main content
14,983,344 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Scenario:

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


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

ASP.NET
<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

C#
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.
Posted
Updated 28-Apr-21 22:01pm
Comments
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[^]
C#
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>";
});
   

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