Search code examples
c#asp.net-core.net-corehtml-helper

Convert a regular string to IHtmlString?


I'm trying to write an extension method for HtmlHelper. It's a modified version of HtmlHelper.Raw(), which looks like the following.

    /// <summary>
    /// Wraps HTML markup in an IHtmlString, which will enable HTML markup to be
    /// rendered to the output without getting HTML encoded.
    /// </summary>
    /// <param name="value">HTML markup string.</param>
    /// <returns>An IHtmlString that represents HTML markup.</returns>
    [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "For consistency, all helpers are instance methods.")]
    public IHtmlString Raw(string value)
    {
        return new HtmlString(value);
    }

So, I tried writing the following.

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Web;

public static class HtmlHelperExtensions
{
    public static IHtmlString Text(this IHtmlHelper helper, string text)
    {
        return new HtmlString(TextToHtml.Transform(text));
    }
}

But the return statement gives me an error.

Cannot implicitly convert type 'Microsoft.AspNetCore.Html.HtmlString' to 'System.Web.IHtmlString'. An explicit conversion exists (are you missing a cast?)

I'm not clear why Microsoft's code works but mine does not. TextToHtml.Transform() returns a regular string. Does anyone know how to convert it to IHtmlString?

Update

I tried a simple cast, but that gives me a runtime error.

System.InvalidCastException: 'Unable to cast object of type 'Microsoft.AspNetCore.Html.HtmlString' to type 'System.Web.IHtmlString'.'


Solution

  • In your code you return a System.Web.IHtmlString, but you are creating inside the method an instance of Microsoft.AspNetCore.Html.HtmlString which does not implement the IHtmlString interface.

    using Microsoft.AspNetCore.Html;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using System.Web;
    
    public static class HtmlHelperExtensions
    {
        public static IHtmlString Text(this IHtmlHelper helper, string text)
        {
            return new HtmlString(TextToHtml.Transform(text));
        }
    }
    

    To fix this you need to decide what you need to return, if you want something that satisfies the IHtmlString interface, you want to return the concrete: System.Web.HtmlString