Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core ToHtmlString

I have the following Kendo UI grid and i need to render an action link for details page:

@(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())

ClientTemplate method expects a html string.

columns.Bound(c => c.Name).ClientTemplate(string template) 

Before .NET Core you'll handle this request in the following manner:

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

Unfortunately .ToHtmlString() (https://msdn.microsoft.com/en-us/library/system.web.htmlstring.tohtmlstring(v=vs.110).aspx) is part of System.Web dll.

How can we handle this in .NET Core?

like image 701
Razvan Dumitru Avatar asked Jun 15 '18 14:06

Razvan Dumitru


1 Answers

I ended up creating an extension method for 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();
        }
    }
}

And I'm using that in my Kendo UI grid in the following manner:

columns.Bound(c => c.Name).ClientTemplate(Html.ActionLink("#=Name#", "Details", new { id = "#=Id#" }).ToHtmlString());
like image 115
Razvan Dumitru Avatar answered Sep 19 '22 19:09

Razvan Dumitru