73

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

120

Try this:

myjavascript( <%= MyBooleanVariableInCSharp.ToString().ToLower() %> );
Sign up to request clarification or add additional context in comments.

3 Comments

It's funny that we must do a so not functional conversion to transform a simple type like boolean but it works! Thanx
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!
worked without <%= %> syntax for me but thanks for the suggestion.
27

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 Comments

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 %>').
@Wynand I edited my answer to clarify that I was offering two separate options
11

You could also do this.

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

Comments

8

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 Comment

var myBoolInJavaScript = @Model.MyBoolInCSharp.ToString().ToLower(); worked like intended. Thank you for this answer
2
function toBool(s){ 
   return s==="True";
}

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.