title: Preventing / understanding xss with javascript encoding
body: <p>I'm currently reading up on .net MVC and have just reached the security chapter of the book.  I've known about xss, and I never trust any user input without sanitizing it first (usually with html encoding or even something like php's strip_tags).  Up until this point I was not familiar with Javascript encoding strings for protection.  One of the examples in the book had a user pass in a string like:</p>
  
  <pre><code>\x3cscript\x3e%20alert(\x27test\x27)\x3c/script\x3e
  </code></pre>
  
  <p>So naturally when I learn something new I want to test it. I created this:</p>
  
  <pre><code>public ActionResult Index()
      {
          ViewBag.test = "\x3cscript\x3e%20alert(\x27test\x27)\x3c/script\x3e";
          return View("index");
      }
  </code></pre>
  
  <p>and this view code that prints out the test string on the page:</p>
  
  <pre><code>@ViewBag.test
  </code></pre>
  
  <p>However, I cannot get this alert box to show at all.  When I view source on the page I get</p>
  
  <pre><code>&amp;lt;script&amp;gt;%20alert(&amp;#39;test&amp;#39;)&amp;lt;/script&amp;gt;
  </code></pre>
  
  <p>I've tried playing with it a few different ways</p>
  
  <ol>
  <li>Passing the @ViewBag from a query string</li>
  <li>putting the viewbag print inside of existing script code (this is how the book had it)</li>
  <li>Replacing the %20 with actual spaces</li>
  <li>Using jquery to replace html with ViewBag.test:<br>
  $('#inject_here').html('@ViewBag.test');</li>
  </ol>
  
  <p>Nothing I try will execute this code (which I guess is a good thing?).  Now I know there wouldn't be a portion of this book dedicated to something that didn't work in the first place, so the problem must be on my end.  I just don't know what it is.  Any one have any ideas?</p>