Fixing Encoded HtmlHelpers in ASP.NET MVC 3

In the process of upgrading one of my projects from ASP.NET MVC 2 to MVC 3 RC, I decided to modify all my views to use the new Razor view engine.  The process has been pretty painless, but one thing I noticed was that the dozen or so HtmlHelpers I built were returning HTML Encoded in my Razor views.

It turns out that using MvcHtmlString or HtmlString instead of String as a return type will prevent double HTML Encoding. Apparently, MvcHtmlString is not automatically encoded, but String is. For example:

public MvcHtmlString GetDiv(this HtmlHelper helper, string value)
{
     string div = "<div>{0}</div>";
     return MvcHtmlHelper.Create(string.Format(div, value));
}

I found a few good questions on StackOverflow with the solution to this problem.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Reddit
  • DotNetKicks
  • Technorati
  • TwitThis

Leave a Reply