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

标签 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);
        }
    }

如何以编程方式呈现局部 View 并将呈现的内容作为 TagHelper.ProcessAsync 中的字符串获取?
我应该请求注入(inject) IHtmlHelper 吗?
是否可以获得对 Razor 引擎的引用?

最佳答案

可以请求在自定义 TagHelper 中注入(inject) 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 方法生成模板。

归功于 frankabbruzzese征求他对 Facility for rendering a partial template from a tag helper 的评论.

关于c# - 如何在 ASP.NET Core 中的自定义 TagHelper 中呈现 Razor 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40438054/

相关文章:

c# - WinSCP SFTP 连接错误

C#:触发事件时的不同语法形式

c# - MVC3 中 UI 的单元测试

jquery - 在 MVC 中将 Json Datetime 分配给 TextBoxFor 时格式错误

c# - 首次操作调用未调用 JwtBearerEvents.OnMessageReceived

c# - 配置 ASP.NET Core 应用程序的正确顺序是什么?

c# - 使用 .NET Core 3.1 和 HttpContext 的客户端 IP 地址错误

c# - 使用数据库保存应用程序设置

C# - Selenium - 重试属性不适用于 Selenium 超时

asp.net-mvc-4 - 在 SelectList 上使用 Html.DropDownList