10

First of all I'm using MVC 3 RC1 with the Razor view engine. I've got an HTML helper extension which looks like this:

public static string TabbedMenuItem(this HtmlHelper htmlHelper, string text, string actionName, string controllerName) {
    StringBuilder builder = new StringBuilder();
    builder.Append("<li>");

    builder.Append(text);

    builder.Append("</li>");
    return builder.ToString();
}

And on the view it's called like this:

@Html.TabbedMenuItem("Home", "Index", "Home")

The problem I've got is that MVC is automatically HTML encoding the result in the view so all I get is the encoded version of the string:

<li>Home</li>

Does anyone know how to disable the automatic encoding for your HTML helper extensions?

Thanks in advance Andy

AndyM
  • 1,148
  • 1
  • 10
  • 19
  • 1
    For future reference, MVC has a System.Web.Mvc.TagBuilder class that you might want to look into. It doesn't negate the needs for returning IHtmlString, but it comes with more functionality than StringBuilder for this sort of task. – Brian Ball Dec 13 '10 at 18:26

2 Answers2

21
public static IHtmlString TabbedMenuItem(this HtmlHelper htmlHelper, string text, string actionName, string controllerName)
{
    StringBuilder builder = new StringBuilder();
    builder.Append("<li>");

    builder.Append(text);

    builder.Append("</li>");
    return MvcHtmlString.Create(builder.ToString());
}

Use return value IHtmlString. Hope this help.

takepara
  • 10,413
  • 3
  • 34
  • 31
  • Should this be `MvcHtmlString` or is that no longer the case in ASP.NET MVC 3? – ehdv Apr 12 '11 at 16:03
  • 1
    @ehdv good question; I googled it and found (this)[http://stackoverflow.com/a/3382908/295686] (HtmlString is preferred in .NET 4+) – mlhDev Jun 07 '13 at 12:01
0

Use TagBuilder

Marcelo Mason
  • 6,750
  • 2
  • 34
  • 43