Passing a boolean value in my .net MVC view to a javascript, but JS doesn't accept True, wants true

If you're using the ToString() method on a .NET boolean to send the value to Javascript, try replacing it with something like

(myBoolean ? "true" : "false")

so that it gets sent to Javascript as the appropriate string representation of the required bool value.

EDIT: Note the difference between:

<script type="text/javascript">
var myBoolean = <%= (myBoolean ? "true" : "false") %>;
</script>

and

<script type="text/javascript">
var myBoolean = '<%= (myBoolean ? "true" : "false") %>';
</script>

In the first example, you end up with:

var myBoolean = false;

and that's a literal Boolean false. In the second, you end up with:

var myBoolean = 'false';

and in JavaScript, 'false' is a non-empty string and consequently if evaluated in a Boolean context, it'll be true. Well, true-ish. :)


I created an extension method to use it in any boolean property of a Model.

    public static class GeneralExtensions
    {
    public static string GetValueForJS(this bool argValue)
        {
            return argValue ? "true" : "false"; 
        }
     }

Now in a view I can simply use:

<script type="text/javascript">
    var variable = @Model.IsFoo.GetValueForJS();
</script>

if you need to do this often, just add this to the top of the javascript (or your js library file, etc.)

var True = true; False = false;

in a simple one off case use:

var x = ('<%= boolValue %>'=='True' );