26

I've got the following custom html helper in asp.net mvc 3

public static string RegisterJS(this HtmlHelper helper, ScriptLibrary scriptLib)
{
   return "<script type=\"text/javascript\"></script>\r\n";
}

The problem is that the result is getting html encoded like so (I had to add spaces to get so to show the result properly:

   &lt;script type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

This obviously isn't much help to me.. Nothing I've read says anything about this.. any thoughts on how I can get my real result back?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Shane Courtrille
  • 13,960
  • 22
  • 76
  • 113

1 Answers1

38

You're calling the helper in a Razor @ block or an ASPX <%: %> block.
These constructs automatically escape their output.

You need to change the helper to return an HtmlString, which will not be escaped:

return new HtmlString("<script ...");
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 2
    Thanks. Is this a change in 3? Even the MS example I found just returned string.. – Shane Courtrille Jan 26 '11 at 20:59
  • @Shane: No; it's a feature of the view engine. – SLaks Jan 26 '11 at 21:01
  • 1
    You might be looking at an example from MVC1. In MVC 2 all helpers got changed to return an HtmlString so that the ASPX auto-encoding feature from .NET 4 could work (using `<%: %>` instead of `<%= %>`). The new Razor view engine automatically encodes everything. – marcind Jan 26 '11 at 21:19