如何在ASP.NET Core中的自定义TagHelper中呈现Razor模板?

时间:2016-11-05 12:06:41

标签: c# razor asp.net-core tag-helpers

我正在创建一个自定义HTML标记助手:

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

2 个答案:

答案 0 :(得分:4)

可以在自定义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 as IViewContextAware).Contextualize(ViewContext);语句。

然后可以使用IHtmlHelper.Partial方法生成模板。

this的评论感谢frankabbruzzese

答案 1 :(得分:2)

在Chedy的答案中添加了一个小(但很重要)的答案(这是正确的答案),此代码可在基类中使用:

public class PartialTagHelperBase : TagHelper
{
    private IHtmlHelper                         m_HtmlHelper;

    public ShopStreetTagHelperBase(IHtmlHelper htmlHelper)
    {
        m_HtmlHelper = htmlHelper;
    }

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    protected async Task<IHtmlContent> RenderPartial<T>(string partialName, T model)
    {
        (m_HtmlHelper as IViewContextAware).Contextualize(ViewContext);

        return await m_HtmlHelper.PartialAsync(partialName, model);
    }
}

因此,继承PartialTagHelperBase可以以非常简单有效的方式帮助呈现部分视图:

        IHtmlContent someContent = await RenderPartial<SomeModel>("_SomePartial", new SomeModel());

        output.PreContent.AppendHtml(someContent);