最近,我遇到了一种情况,我希望在标记助手中使用标记助手。我环顾四周,发现没有其他人试图这么做,我是在使用糟糕的会议,还是丢失了文档?
例如。Tag helper --输出包含另一个标记助手的HTML。
例如。
[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?
发布于 2017-02-02 19:42:30
不你不能。TagHelpers是Razor解析时间特性。
另一种选择是创建一个TagHelper并手动调用它的ProcessAsync/Process方法。又名:
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);发布于 2018-05-08 21:52:29
如果有人希望重用来自asp.net核心的内置标记帮助程序,则可以使用IHtmlGenerator。对于重用其他类型的标记帮助程序,我还没有找到一个更简单的选项:@N. Taylor Mullen答案
下面是如何重用asp-action标记助手:
[HtmlTargetElement("helplink")]
public class RazorTagHelper : TagHelper
{
private readonly IHtmlGenerator _htmlGenerator;
public RazorTagHelper(IHtmlGenerator htmlGenerator)
{
_htmlGenerator = htmlGenerator;
}
[ViewContext]
public ViewContext ViewContext { set; get; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "div";
output.TagMode = TagMode.StartTagAndEndTag;
var actionAnchor = _htmlGenerator.GenerateActionLink(
ViewContext,
linkText: "Home",
actionName: "Index",
controllerName: null,
fragment: null,
hostname: null,
htmlAttributes: null,
protocol: null,
routeValues: null
);
var builder = new HtmlContentBuilder();
builder.AppendHtml("Here's the link: ");
builder.AppendHtml(actionAnchor);
output.Content.SetHtmlContent(builder);
}
}发布于 2017-10-16 15:30:48
我不知道这是否适用于您的场景,但是可以从AnchorTagHelper继承,然后像这样进行定制。
public class TestTagHelper : AnchorTagHelper
{
public TestTagHelper(IHtmlGenerator htmlGenerator) : base(htmlGenerator) { }
public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
// Replaces <test> with <a> tag
output.TagName = "a";
// do custom processing
output.Attributes.SetAttribute("class", "custom-class");
// let the base class generate the href
// note the base method may override your changes so it may be
// preferable to call it first instead of last.
await base.ProcessAsync(context, output);
}
}然后,您可以在视图中使用这个标记助手,并使用默认AnchorTagHelper的所有内置优点。
<test asp-action="Index" asp-route-id="5"></test>https://stackoverflow.com/questions/42010429
复制相似问题