68

Having issues where in my .aspx page I pass in a boolean variable (C#) to a javascript function that is expecting a boolean type.

BUt the C# variable returns True, and javascript doesn't like the uppercase.

myjavascript( <%= MyBooleanVariableInCSharp %> );

If I convert the c# variable to string, then my javascript variable becomes a string and not a js bool value!

what is the solution to this nightmare? lol

5 Answers 5

117

Try this:

myjavascript( <%= MyBooleanVariableInCSharp.ToString().ToLower() %> );
3
  • 3
    It's funny that we must do a so not functional conversion to transform a simple type like boolean but it works! Thanx
    – Samuel
    Aug 3, 2012 at 1:02
  • Wow, how stupid. Having to turn a boolean to a string and then making it lower to compare it to a javascript boolean. It works though. Thanks!
    – IamBatman
    Jan 15, 2019 at 17:55
  • worked without <%= %> syntax for me but thanks for the suggestion. Mar 13, 2019 at 17:59
26

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;

Then you code

myjavascript( <%= MyBooleanVariableInCSharp %> );

Would work just fine.

Another option if for whatever reason you don't want to use the variables is to write your javascript call like this:

myjavascript( '<%= MyBooleanVariableInCSharp %>'=='True' );
2
  • 1
    Good idea, although this will end up on the page as myjavascript('True' == 'True'), which doesn't require the use of variables. If you had myjavascript(<%= MyBooleanVariableInCSharp %> == 'True') in mind, the variables are required but it will never evaluate to true. Another idea based on yours: myjavascript('<%= MyBooleanVariableInCSharp %>' === '<%= bool.TrueString %>').
    – WynandB
    Sep 19, 2013 at 1:49
  • @Wynand I edited my answer to clarify that I was offering two separate options
    – mendel
    Sep 22, 2013 at 3:07
11

You could also do this.

myjavascript(<%=myBooleanVariableInCSharp ? "true" : "false" %>);
7

The other answers are targeting the old version, before Razor
if you are using Razor then this is the solution

myjavascript( @MyBooleanVariableInCSharp.ToString().ToLower() );
1
  • var myBoolInJavaScript = @Model.MyBoolInCSharp.ToString().ToLower(); worked like intended. Thank you for this answer Jun 14, 2018 at 12:38
2
function toBool(s){ 
   return s==="True";
}

var b = toBool("@csharpvariable.ToBoolean()");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.