title: Escaping JavaScript string literals in views
body: <p>Is there a utility function for escaping JavaScript in ASP.NET MVC views? I often need to init a little snippet of JavaScript using some values from the view; for instance I may have something like:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  var page = new Page({ currentUser: "&lt;%= Model.UserName %&gt;" });
  page.init();
  &lt;/script&gt;
  </code></pre>
  
  <p>I would expect something like:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  var page = new Page({ currentUser: "&lt;%= Html.JavaScriptEscape(Model.UserName) %&gt;" });
  page.init();
  &lt;/script&gt;
  </code></pre>
  
  <p>I could, of course, write the function myself. But since there are already built-in utilities form HTML encoding, and since one of the selling points of ASP.NET MVC is that the &lt;% %> is the default rendering mode, and since what I'm trying to achieve is quite common, it makes me wonder why I cannot find anything like that already built-in. Is there, for instance, an easy and elegant way to serialize an object to JSON in views?</p>
  
  <p>Or am doing something against ASP.NET MVC principles? When I hit a problem like this, it usually makes it think that either I’m doing something wrong since I assume that the framework designers spent some time thinking about real world scenarios.</p>