The documentation for MvcHtmlString is not terribly enlightening:
Represents an HTML-encoded string that should not be encoded again.
It’s not clear to me what exactly the implications of this are. It seems that some HTML helper methods return an MvcHtmlString, but several examples I’ve seen online of custom helpers just return a regular string.
Questions:
What is an MvcHtmlString?
When should I choose MvcHtmlString over string and vice versa? Why?
ASP.NET 4 introduces a new code nugget syntax
<%: %>. Essentially,<%: foo %>translates to<%= HttpUtility.HtmlEncode(foo) %>. The team is trying to get developers to use<%: %>instead of<%= %>wherever possible to prevent XSS.However, this introduces the problem that if a code nugget already encodes its result, the
<%: %>syntax will re-encode it. This is solved by the introduction of the IHtmlString interface (new in .NET 4). If the foo() in<%: foo() %>returns an IHtmlString, the<%: %>syntax will not re-encode it.MVC 2’s helpers return MvcHtmlString, which on ASP.NET 4 implements the interface IHtmlString. Therefore when developers use
<%: Html.*() %>in ASP.NET 4, the result won’t be double-encoded.Edit:
An immediate benefit of this new syntax is that your views are a little cleaner. For example, you can write
<%: ViewData["anything"] %>instead of<%= Html.Encode(ViewData["anything"]) %>.