以编程方式使用 AnchorTagHelper 的输出

Use the output of an AnchorTagHelper programmatically

提问人:drewta 提问时间:5/25/2023 最后编辑:drewta 更新时间:5/25/2023 访问量:28

问:

我在以编程方式处理 AnchorTagHelper 的结果时遇到问题。我知道如何直接在 Razor 标记中使用它,但我想获取 AnchorTagHelper 的 HTML 输出,然后在字符串中将其替换为占位符。

下面是简化的用例。想象一个无头 CMS,营销用户可以在页面上自定义潜在客户表单。在提交表格之前,消费者必须同意某些法律政策。我想让 CMS 用户能够为协议文本复选框撰写文本。文本应包括基本的纯文本(“我同意......”)和指向 0 个或多个相关法律页面的链接(条款和条件、隐私政策、加州居民隐私政策等)。因此,他们可能会输入如下内容,其中用双括号括起来的值应替换为指向指定页面的锚标记:

我同意 [[TermsAndConditions]] 和 [[PrivacyPolicy]]

不幸的是,需要使用 AnchorTagHelper 来构造 Razor 页面中的链接,因为该站点可能支持不同的国家/语言,因此我需要以编程方式获取当前区域性的正确路由。

以下代码显示了一种简化的方法,其中路由数据是硬编码的,而不是来自无外设 CMS。显示的逻辑无法编译,但它代表了我想要实现的目标。谁能提出一种方法来获得所需的输出?agreementText.Replace

// 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>
剃刀页 asp.net-core-tag-helpers

评论

0赞 Mike Brind 5/25/2023
也许您可以将 AnchorTagHelper 子类化并将 PlaceHolder 属性添加到您的版本中?

答: 暂无答案