I'm having trouble working programmatically with the results of the AnchorTagHelper. I know how to use it directly within Razor markup, but I'd like get the HTML output of the AnchorTagHelper and then substitute it within a string for a placeholder.
Here's the simplified use case. Imagine a headless CMS where marketing users can customize a lead form on a page. Before submitting the form, the consumer must agree to certain legal policies. I'd like to give CMS users the ability to compose the text for an agreement checkbox. The text should include basic plain text ("I agree to...") and links to 0 or more legal pages that are relevant (Terms and Conditions, Privacy Policy, Privacy Policy for California Residents, etc.). So, they might enter something like this, where the values enclosed by double brackets should be replaced by anchor tags leading to the specified pages:
I agree to the [[TermsAndConditions]] and [[PrivacyPolicy]]
Unfortunately, using an AnchorTagHelper to construct the links in the Razor page is required because the site supports may different countries/languages, so I need to programmatically get the correct route for the current culture.
The following code shows a simplified approach where the route data is hard-coded rather than coming from the headless CMS. The agreementText.Replace logic shown doesn't compile, but it represents what I'm trying to achieve. Can anyone suggest a way to get the desired output?
// POCO for links to legal pages
public class LegalRoute
{
public string Id { get; set; }
public string Text { get; set; }
public string Placeholder { get; set; }
}
// Razor page view
@{
var route1 = new LegalRoute
{
Id = "1234",
Text = "Terms and Conditions",
Placeholder = "[[TermsAndConditions]]"
};
var route2 = new LegalRoute
{
Id = "5678",
Text = "Privacy Policy",
Placeholder = "[[PrivacyPolicy]]"
};
var routes = List<LegalRoute> { route1, route2 };
var agreementText =
"I agree to the [[TermsAndConditions]] and [[PrivacyPolicy]]";
foreach (var route in routes)
{
// Replace doesn't actually work
agreementText = agreementText.Replace(route.Placeholder,
@<a asp-route="@route.Id" asp-route-culture="@Culture.Current">@Html.Raw(route.Text)</a>);
}
}
<label>
@Html.Raw(agreementText)
@* Output should look like this if the culture is en-us:
I agree to the <a href="/terms-and-conditions">TermsAndConditions</a> and <a href="/privacy-policy">Privacy Policy</a>
*@
@* Output should look like this if the culture is en-au:
I agree to the <a href="/au/terms-and-conditions">TermsAndConditions</a> and <a href="/au/privacy-policy">Privacy Policy</a>
*@
<input type="checkbox" required>
<span class="checkmark"></span>
</label>