title: MVC 3 Razor View: Generating JavaScript from a boolean model value
body: <p>I am using ASP.Net MVC 3 Razor view engine.</p>
  
  <p>I have a requirement to generate some JavaScript code in my View based on a value in my View Model. The value I need to use is a boolean, for this example lets call it <code>IsSet</code>.</p>
  
  <p>So what I want to do is create a JavaScript boolean based on this value that I can use in the script later on.</p>
  
  <p>Keep in mind that for all below examples I have this bit of code at the top of my view...</p>
  
  <pre><code>@{ string IsSet = Model.IsSet  ? "true" : "false"; }
  </code></pre>
  
  <p><strong>NOTE</strong>: All examples below are JavaScript.</p>
  
  <p><strong>First attempt</strong>...</p>
  
  <pre><code>var IsSet = @(IsSet);
  </code></pre>
  
  <p>... this actually works, the <strong>problem is it breaks the auto-formatting</strong> (CTRL + E, D) in VS 2010 due to badly formatted JavaScript - as you might expect, and this is not acceptable.</p>
  
  <p><strong>Second attempt</strong>...</p>
  
  <pre><code>var IsSet = "@(IsSet)";
  </code></pre>
  
  <p>...I know, JavaScript is clever, it will auto-parse my string when needed. Ooops, forgot it is a string type and anything other than empty evaluates to true.</p>
  
  <p><strong>Third attempt</strong>...</p>
  
  <pre><code>var IsSet = Boolean("@(IsSet)");
  </code></pre>
  
  <p>....surely this will work... nope, convert non-empty string to true again (bad parser!)</p>
  
  <p><strong>Fourth attempt</strong>...</p>
  
  <pre><code>var IsSet = "@(IsSet)" === "true";
  </code></pre>
  
  <p>Finally something that works, but it doesn't look great to me.</p>
  
  <p>I will use this if need be but ultimately my question is: Is there a better way to handle this kind of situation? Perhaps, the unwanted behaviour in my first attempt is just something that Microsoft may have overlooked?</p>
  
  <p>If anybody has a nice and tidy fifth attempt for me, that would be good.</p>
  
  <p><strong>The important thing for me is that the auto-formatting in VS 2010 does not break</strong></p>
  
  <p>Thanks</p>