AspCore ViewComponent with StreamResult
本文关键字:StreamResult with ViewComponent AspCore | 更新日期: 2023-09-27 17:53:00
当我有一个ViewComponent,它可以返回一个视图。
但是它被绑定到视图文件夹中的一个文件,像这样
public class ContactViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
return View();
}
}
现在我想通过一个包含视图标记的给定字符串来创建ViewContent。
是否有一个内置的方法来做到这一点与视图组件?
用HtmlContent
返回HtmlContentViewComponentResult
应该可以达到目的。
public class ContactViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
var htmlString = new HtmlString("<b>Hello World!</b>");
return new HtmlContentViewComponentResult(htmlString);
}
}
HtmlString
返回未转义的原始字符串。但是要小心,不要让人们将恶意代码注入到这里呈现的内容中!
资源链接:
https://github.com/aspnet/Mvc/blob/a78f77afde003c4a3fcf5dd7b6dc13dd9c85f825/src/Microsoft.AspNetCore.Mvc.ViewFeatures/ViewComponents/HtmlContentViewComponentResult.cs https://github.com/aspnet/HtmlAbstractions/blob/dev/src/Microsoft.AspNetCore.Html.Abstractions/HtmlString.cs