从ViewComponent返回自定义html

Sam*_*Sam 4 c# asp.net-core asp.net-core-viewcomponent

在ASP.NET Core应用程序中,我想从ViewComponent返回自定义html.我可以返回自定义文本,但html将被编码而不是嵌入:

public class BannerViewComponent : ViewComponent
{
  public async Task<IViewComponentResult> InvokeAsync(string param1, int param2)
  {
    return Content("<strong>some custom html</strong>");
  }
}
Run Code Online (Sandbox Code Playgroud)

我在.cshtml页面中使用它:

    @await Component.InvokeAsync("BannerView")
Run Code Online (Sandbox Code Playgroud)

在页面上,这将显示为<strong>some custom html</strong>而不是一些自定义的HTML.
如何从ViewComponent直接返回HTML而不是文本?

b.p*_*ell 8

如果您不想返回视图,则可以在没有视图的情况下以这种方式返回HTML:

return new HtmlContentViewComponentResult(new HtmlString("Not bold - <b>bold</b>"));
Run Code Online (Sandbox Code Playgroud)


tru*_*dia 5

您的 ViewComponent 也可以有自己的视图,您可以在那里呈现 html。解决方案如下:

public class BannerViewComponent : ViewComponent
{
  public async Task<IViewComponentResult> InvokeAsync(string param1, int param2)
  {
    string model = "<strong>some custom html</strong>";
    return View("Index", model);
  }
}
Run Code Online (Sandbox Code Playgroud)

将以下内容添加到您的 Views 文件夹中:Views\Shared\Components\BannerViewComponent\Index.cshtml并将以下内容放入 ViewComponent 的视图中:

@model string
@Html.Raw(Model)
Run Code Online (Sandbox Code Playgroud)

您可以将模型更改为一个类,而不仅仅是一个字符串,以便您可以构建 ViewComponent 的输出,但关键部分是Html.Raw()输出未编码 html的方法。