我正在创建一个自定义HTML Tag Helper:
public class CustomTagHelper : TagHelper
{
[HtmlAttributeName("asp-for")]
public ModelExpression DataModel { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
string content = RazorRenderingService.Render("TemplateName", DataModel.Model);
output.Content.SetContent(content);
}
}
如何以编程方式呈现部分视图并在TagHelper.ProcessAsync中以字符串形式获取呈现的内容?
我应该请求注入IHtmlHelper吗?
是否有可能获得剃须刀引擎的参考?
解决方法:
可以在自定义TagHelper中请求注入IHtmlHelper:
public class CustomTagHelper : TagHelper
{
private readonly IHtmlHelper html;
[HtmlAttributeName("asp-for")]
public ModelExpression DataModel { get; set; }
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
public CustomTagHelper(IHtmlHelper htmlHelper)
{
html = htmlHelper;
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
//Contextualize the html helper
(html as IViewContextAware).Contextualize(ViewContext);
var content = await html.PartialAsync("~/Views/path/to/TemplateName.cshtml", DataModel.Model);
output.Content.SetHtmlContent(content);
}
}
提供的IHtmlHelper实例尚未准备好使用,需要对其进行上下文化,因此(html格式为IViewContextAware).Contextualize(ViewContext);声明.
然后可以使用IHtmlHelper.Partial方法生成模板.
对于他对Facility for rendering a partial template from a tag helper的评论,功劳达到frankabbruzzese.