Can I use a Tag Helper in a custom Tag Helper that returns html?(我可以在返回 html 的自定义 Tag Helper 中使用 Tag Helper 吗?)
问题描述
我最近遇到了一种情况,我想在标签助手中使用标签助手.我环顾四周,找不到其他人尝试这样做,是我使用了糟糕的约定还是缺少文档?
I recently ran into a situation where I would like to use a tag helper within a tag helper. I looked around and couldn't find anyone else trying to do this, am I using a poor convention or am I missing documentation?
例如.标签助手 A 输出包含另一个标签助手的 HTML.
Ex. Tag Helper A outputs HTML that contains another tag helper.
例如.
[HtmlTargetElement("tag-name")]
public class RazorTagHelper : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
StringBuilder sb = new StringBuilder();
sb.Append("<a asp-action="Home" ");
output.Content.SetHtmlContent(sb.ToString());
}
}
有没有办法让我处理 <a asp-action></a>
来自 C# 的标签助手?还是用标签助手重新处理输出的 HTML?
Is there a way for me to process the <a asp-action> </a>
tag helper from C#? Or to reprocess the output HTML with tag helpers?
推荐答案
不,你不能.TagHelpers 是 Razor 解析时间功能.
No you cannot. TagHelpers are a Razor parse time feature.
另一种方法是创建 TagHelper 并手动调用其 ProcessAsync/Process 方法.又名:
One alternative is creating a TagHelper and manually invoking its ProcessAsync/Process method. Aka:
var anchorTagHelper = new AnchorTagHelper
{
Action = "Home",
};
var anchorOutput = new TagHelperOutput("a", new TagHelperAttributeList(), (useCachedResult, encoder) => new HtmlString());
var anchorContext = new TagHelperContext(
new TagHelperAttributeList(new[] { new TagHelperAttribute("asp-action", new HtmlString("Home")) }),
new Dictionary<object, object>(),
Guid.NewGuid());
await anchorTagHelper.ProcessAsync(anchorContext, anchorOutput);
output.Content.SetHtmlContent(anchorOutput);
这篇关于我可以在返回 html 的自定义 Tag Helper 中使用 Tag Helper 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以在返回 html 的自定义 Tag Helper 中使用 Tag Helper 吗?


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01