如何在ASP中自定义TagHelper中呈现Razor模板.净的核心
本文关键字:模板 Razor 核心 TagHelper ASP 自定义 | 更新日期: 2023-09-27 18:16:22
我正在创建一个自定义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吗?
是否有可能得到剃刀引擎的参考?
可以在自定义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
方法生成模板。
感谢frankabbruzzese对Facility的评论,该工具可以从标记帮助器中呈现部分模板。
为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);