2016-11-05 52 views
3

我创建一个自定义HTML代码助手:如何在ASP.NET Core的自定义TagHelper中渲染Razor模板?

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?
是否有可能获得对剃刀引擎的参考?

回答

3

它可以请求IHtmlHelper注射自定义TagHelper:

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 as IViewContextAware).Contextualize(ViewContext);声明。

IHtmlHelper.Partial方法然后可以用于产生模板。

幸得frankabbruzzese为他的Facility for rendering a partial template from a tag helper评论。

+0

这被认为是不好的做法?我们应该在我们的TagHelpers中使用IHtmlHelper吗? – Dave

+1

@Dave实际上它可能是一个不好的做法,因为[View Components](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components)存在。 – Chedy2149