【问题标题】:return custom html from ViewComponent从 ViewComponent 返回自定义 html
【发布时间】:2017-02-01 14:40:47
【问题描述】:

在 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>");
  }
}

我在我的 .cshtml 页面中使用它:

    @await Component.InvokeAsync("BannerView")

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

【问题讨论】:

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


    【解决方案1】:

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

    return new HtmlContentViewComponentResult(new HtmlString("Not bold - <b>bold</b>"));
    

    【讨论】:

      【解决方案2】:

      您的 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);
        }
      }
      

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

      @model string
      @Html.Raw(Model)
      

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

      【讨论】:

        【解决方案3】:

        虽然我建议在大多数情况下使用视图(并将所有 HTML 放在视图中,而不是仅使用它来输出视图组件创建的 HTML),但对于非常简单的组件,您可能需要考虑以下内容:

        视图组件上的Invoke()方法不需要返回IViewComponentResult,可以返回HtmlString

        例如:

        public HtmlString Invoke()
        {
            return new HtmlString(@"<b>Hello World</b>");
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-12
          • 1970-01-01
          • 1970-01-01
          • 2020-09-08
          相关资源
          最近更新 更多