Custom HtmlHelper Renders Text and not Markup
Asked Answered
I

4

19

I have written a basic HtmlHelper. Here's a test I wrote that simplifies what I was doing and to provide self assurance that it is happening when I use StringBuilder and TagBuilder objects:

public static string HelloWorld(this HtmlHelper htmlHelper, string name)
{
    var sb = new StringBuilder();
    var builder = new TagBuilder("span");
    builder.InnerHtml = "Hello, " + name + "!";
    sb.Append(builder.ToString(TagRenderMode.Normal));
    sb.Append("<br/>");

    return sb.ToString();
}

The output for this control encodes the string so I see the following: <span>Hello, Jason!</span><br/>

In my view, I'm using the following: @Html.HelloWorld("Jason")

Any ideas what I can be doing wrong?

Inquisitionist answered 5/8, 2011 at 2:53 Comment(0)
H
23

The Razor engine escapes HTML by default in any strings that it renders. If you change the return type to IHtmlString, this won't happen.

public static IHtmlString HelloWorld(this HtmlHelper htmlHelper, string name)
    ...
    return new HtmlString(sb.ToString());
}
Heir answered 5/8, 2011 at 2:59 Comment(1)
Thanks. I had to set the method return type to HtmlString too.Inquisitionist
P
3

Your static method must be HtmlString instead of string, and you must return the HtmlString(sb.ToString());

public static HtmlString HelloWorld(this HtmlHelper htmlHelper, string name)
{
    var sb = new StringBuilder();
    var builder = new TagBuilder("span");
    builder.InnerHtml = "Hello, " + name + "!";
    sb.Append(builder.ToString(TagRenderMode.Normal));
    sb.Append("<br/>");

    return new HtmlString(sb.ToString());
}
Porringer answered 5/8, 2011 at 3:1 Comment(1)
Thanks. I had to cast my return as an HtmlString as well.Inquisitionist
K
1

Use AppendFormat instead of Append

var sb = new StringBuilder();
    var builder = new TagBuilder("span");
    builder.InnerHtml = "Hello, " + name + "!";
    sb.AppendFormat(builder.ToString(TagRenderMode.Normal));
    sb.AppendFormat("<br/>");

    return sb.ToString();
Kassab answered 5/8, 2011 at 2:58 Comment(0)
W
0

Here is an answer for the year 2018 working with .Net Core 2

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

public static IHtmlContent HelloWorld(this IHtmlHelper html, string name)
{
    var span = new TagBuilder("span");
    span.InnerHtml.Append("Hello, " + name + "!");

    var br = new TagBuilder("br") {TagRenderMode = TagRenderMode.SelfClosing};

    string result;

    using (var writer = new StringWriter())
    {
        span.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default);
        br.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default);
        result = writer.ToString();
    }

    return new HtmlString(result);
}
Wiltshire answered 8/8, 2018 at 14:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.