使用StreamResult的AspCore ViewComponent

时间:2016-06-29 12:50:08

标签: c# asp.net-core asp.net-core-viewcomponent

当我有一个ViewComponent时,它可以返回一个视图。

但是它绑定到视图文件夹中的文件,如此

public class ContactViewComponent : ViewComponent
{
    public IViewComponentResult Invoke()
    {
        return View();
    }
}

现在我想通过包含视图标记的给定字符串创建ViewContent。

是否有一种内置方法可以使用视图组件执行此操作?

1 个答案:

答案 0 :(得分:1)

使用HtmlContentViewComponentResult返回HtmlContent应该可以解决问题。

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

相关问题