I am using ASP.Net MVC 3 Razor view engine.
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 IsSet.
So what I want to do is create a JavaScript boolean based on this value that I can use in the script later on.
Keep in mind that for all below examples I have this bit of code at the top of my view...
@{ string IsSet = Model.IsSet ? "true" : "false"; }
NOTE: All examples below are JavaScript.
First attempt...
var IsSet = @(IsSet);
... this actually works, the problem is it breaks the auto-formatting (CTRL + E, D) in VS 2010 due to badly formatted JavaScript - as you might expect, and this is not acceptable.
Second attempt...
var IsSet = "@(IsSet)";
...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.
Third attempt...
var IsSet = Boolean("@(IsSet)");
....surely this will work... nope, convert non-empty string to true again (bad parser!)
Fourth attempt...
var IsSet = "@(IsSet)" === "true";
Finally something that works, but it doesn't look great to me.
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?
If anybody has a nice and tidy fifth attempt for me, that would be good.
The important thing for me is that the auto-formatting in VS 2010 does not break
Thanks