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

编程入门 行业动态 更新时间:2024-10-12 12:22:59
本文介绍了如何在ASP.NET Core中的自定义TagHelper中呈现Razor模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在创建自定义HTML标记帮助器:

I am creating a custom 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吗? 有可能获得剃须刀引擎的参考吗?

How to render a partial view programatically an get the rendered content as a string inside TagHelper.ProcessAsync ? Should I request the injection of an IHtmlHelper ? Is it possible to get a reference to the razor engine ?

推荐答案

可以在自定义TagHelper中请求注入IHtmlHelper:

It is possible to request the injection of an IHtmlHelper in the custom 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);语句.

The IHtmlHelper instance provided is not ready for use and it is necessary to contextualize it, hence the (html as IViewContextAware).Contextualize(ViewContext); statement.

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

The IHtmlHelper.Partial method can then be used to generate the template.

信贷请 frankabbruzzese 对从标记帮助程序呈现部分模板的功能.

更多推荐

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

本文发布于:2023-11-14 03:58:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586152.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   模板   如何在   ASP   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!