ASP.NET Core ToHtmlString

Raz*_*tru 2 c# kendo-ui asp.net-core-mvc asp.net-core

我具有以下Kendo UI网格,我需要为详细信息页面呈现一个操作链接:

@(Html.Kendo().Grid<Model>()
  .Name("grid")
  .Columns(columns =>
  {
      columns.Bound(c => c.Id).Hidden(true);

      @* Invalid line of code as ClientTemplate is waiting for a string *@
      columns.Bound(c => c.Name).ClientTemplate(Html.ActionLink("#=Name#", "Details", new { id = "#=Id#" }));
      @* Invalid line of code as ClientTemplate is waiting for a string *@

      columns.Bound(c => c.Type).Width(100);
      columns.Bound(c => c.Subdomain).Width(150);
      columns.Bound(c => c.Description);
      columns.Bound(c => c.Status).Width(100);
      columns.Select().Width(50);
  })
  .AutoBind(false)
  .Scrollable()
  .Pageable(pageable => pageable
      .Refresh(false)
      .PageSizes(true)
      .ButtonCount(5))
  .DataSource(dataSource => dataSource
      .Ajax()
      .Read(read => read.Action("Read", "Data"))
      .PageSize(5)).Deferred())
Run Code Online (Sandbox Code Playgroud)

ClientTemplate 方法需要一个html字符串。

columns.Bound(c => c.Name).ClientTemplate(string template) 
Run Code Online (Sandbox Code Playgroud)

在.NET Core之前,您将通过以下方式处理此请求:

  columns.Bound(c => c.Name).ClientTemplate(Html.ActionLink("#=Name#", "Details", new { id = "#=Id#" }).ToHtmlString());
Run Code Online (Sandbox Code Playgroud)

不幸的是.ToHtmlString()https://msdn.microsoft.com/zh-cn/library/system.web.htmlstring.tohtmlstring(v=vs.110).aspx)是System.Webdll的一部分。

我们如何在.NET Core中处理此问题?

Raz*_*tru 8

我最终为创建了一个扩展方法IHtmlContent

public static class HtmlContentExtensions
{
    public static string ToHtmlString(this IHtmlContent htmlContent)
    {
        if (htmlContent is HtmlString htmlString)
        {
            return htmlString.Value;
        }

        using (var writer = new StringWriter())
        {
            htmlContent.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default);
            return writer.ToString();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我以下列方式在Kendo UI网格中使用它:

columns.Bound(c => c.Name).ClientTemplate(Html.ActionLink("#=Name#", "Details", new { id = "#=Id#" }).ToHtmlString());
Run Code Online (Sandbox Code Playgroud)

  • 如果 IHtmlContent 是 HtmlString 的实例,则只需获取 value 属性即可。因此,在我的扩展方法版本中,我在使用之前添加了以下内容: if (htmlContent is HtmlString htmlString) { return htmlString.Value; } (3认同)