问题描述
我正在编写一个自定义TagHelper,并希望在其中渲染一个ViewComponent。
类似于vc:xyz标记帮助器所做的事情,但是以更受控的方式进行,以便我可以在运行时确定要呈现哪个ViewComponent。
I'm writing a custom TagHelper and want to render a ViewComponent inside it. Something similar to what vc:xyz tag helper does, but in a more controlled way, so that I can determine at runtime which ViewComponent to render.
有可能吗?
推荐答案
为此,您需要将IViewComponentHelper注入TagHelper,对其进行上下文化,然后使用它呈现任何ViewComponent。取决于您的应用程序逻辑。这是一个简单的例子:
In order to do that, you need to inject IViewComponentHelper into your TagHelper, contextualize it and then use it to render any ViewComponent depending on your application logic. Here is a quick illustration:
[HtmlTargetElement("widget", Attributes = WidgetNameAttributeName)]
public class WidgetTagHelper : TagHelper
{
private const string WidgetNameAttributeName = "name";
private readonly IViewComponentHelper _viewComponentHelper;
public WidgetTagHelper(IViewComponentHelper viewComponentHelper)
{
_viewComponentHelper = viewComponentHelper;
}
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
[HtmlAttributeName(WidgetNameAttributeName)]
public string Name { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
((IViewContextAware)_viewComponentHelper).Contextualize(ViewContext);
var content = await _viewComponentHelper.InvokeAsync(typeof(WidgetViewComponent), new { name = Name });
output.Content.SetHtmlContent(content);
}
}
此外,请记住,自闭合标签会无效:
Also, keep in mind that self-closing tags will NOT work:
<widget name="abc" />
请改用以下表格:
<widget name="abc"></widget>
这篇关于是否可以从自定义TagHelper调用ViewComponent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!