Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom HtmlHelper Renders Text and not Markup

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?

like image 940
Jason N. Gaylord Avatar asked Aug 05 '11 02:08

Jason N. Gaylord


People also ask

What is the difference between tag helper and HTML helper?

Tag Helpers are attached to HTML elements inside your Razor views and can help you write markup that is both cleaner and easier to read than the traditional HTML Helpers. HTML Helpers, on the other hand, are invoked as methods that are mixed with HTML inside your Razor views.

How can I create my own Htmlhelper?

There are two ways in MVC to create custom Html helpers as below. We can create our own HTML helper by writing extension method for HTML helper class. These helpers are available to Helper property of class and you can use then just like inbuilt helpers. Add new class in MVC application and give it meaningful name.

What is inline HTML helpers in MVC?

What is Inline HTML Helper in MVC 5? Inline HTML Helper is used to create a reusable Helper method by using the Razor @helper tag. Inline helpers can be reused only on the same view. We can not use Inline helper to the different view Pages. We can create our own Inline helper method based on our requirements.


2 Answers

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());
}
like image 183
StriplingWarrior Avatar answered Sep 30 '22 11:09

StriplingWarrior


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());
}
like image 25
Chase Florell Avatar answered Sep 30 '22 09:09

Chase Florell