Friday, February 11, 2011

HtmlHelper extension method output unencoded strings in ASP.NET MVC 3.0 Razor views

In ASP.NET MVC 1.0 when using the <%= tag you had to handle any string html encoding you wanted specifically.

This was changed in ASP.NET 2.0 when generated views introduced the <%: tag which by default would html encode your string. In ASP.NET MVC 2.0 you could use the MvcHtmlString class which allowed you to avoid html encoding a string.

With .NET 4.0 you now have another option for not html encoding strings (for instance from an HtmlHelper extension method used in a ASP.NET MVC 3.0 Razor view). The interface IHtmlString and the implementing class HtmlString allows you to indicate that a string is not to be html encoded.

public static class HtmlHelperExtensions
{
    // .NET 4.0
    public static IHtmlString EmitObjectTagUnencoded(this HtmlHelper htmlHelper, string someValue)
    {
        return new HtmlString(string.Format("<object>{0}</object>", someValue));
    }

    // ASP.NET MVC 2 
    public static MvcHtmlString EmitObjectTagUnencoded2(this HtmlHelper htmlHelper, string someValue)
    {
        return MvcHtmlString.Create(string.Format("<object>{0}</object>", someValue));
    }

    public static string EmitObjectTagEncoded(this HtmlHelper htmlHelper, string someValue)
    {
        return string.Format("<object>{0}</object>", someValue);
    }
}
Using this in a view like the following
<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
       @Html.EmitObjectTagUnencoded("EmitObjectTagUnencoded")
    </div>
    <div>
       @Html.EmitObjectTagUnencoded2("EmitObjectTagUnencoded2")
    </div>
    <div>
       @Html.EmitObjectTagEncoded("EmitObjectTagEncoded")
    </div>
</body>
</html>
Will yield the following html output
<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
       <object>EmitObjectTagUnencoded</object>
    </div>

    <div>
       <object>EmitObjectTagUnencoded2</object>
    </div>
    <div>
       &lt;object&gt;EmitObjectTagEncoded&lt;/object&gt;
    </div>
</body>

</html>
Post a Comment