Search code examples
asp.net-mvcasp.net-mvc-3razorhtml-encodehtml-helper

HTML Encoding for HtmlHelper Extension Method


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


Solution

  • 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.