使用RC1,您可以构建一个新的TagBuilder,并将其附加到自定义TagHelper的输出中:
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var indicator = new TagBuilder("span");
indicator.AddCssClass("indicator");
output.Content.Append(indicator);
}
现在,RC2失败,因为TagHelperOutput.Content.Append()
只接受string
。
我可以和TagBuilder.WriteTo()
混淆,但与它的情况相比,这似乎过于复杂。
是否有新方法构建新标记并附加到我错过的输出中?
答案 0 :(得分:4)
在RC2中,您可以使用
output.Content.AppendHtml(tag);
菜单标签助手示例:
视图:
<ul>
<menu action="Index" controller="Home">Home page</menu>
<menu action="List" controller="Home">List</menu>
</ul>
MenuTagHelper.cs:
[HtmlTargetElement(Attributes = "controller, action")]
public class MenuTagHelper : TagHelper
{
public string Controller { get; set; }
public string Action { get; set; }
[ViewContext]
public ViewContext ViewContext { get; set; }
private readonly IUrlHelperFactory urlHelperFactory;
public MenuTagHelper(IUrlHelperFactory urlHelperFactory)
{
this.urlHelperFactory = urlHelperFactory;
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var sb = new StringBuilder();
var urlHelper = urlHelperFactory.GetUrlHelper(ViewContext);
var url = urlHelper.Action(Action, Controller);
var text = (await output.GetChildContentAsync()).GetContent();
output.TagName = "li";
var a = new TagBuilder("a");
a.MergeAttribute("href", $"{url}");
a.MergeAttribute("title", text);
a.InnerHtml.Append(text);
var routeData = ViewContext.RouteData.Values;
var currentController = routeData["controller"];
var currentAction = routeData["action"];
if (string.Equals(Action, currentAction as string, StringComparison.OrdinalIgnoreCase) && string.Equals(Controller, currentController as string, StringComparison.OrdinalIgnoreCase))
output.Attributes.Add("class", "active");
output.Content.AppendHtml(a);
}
}