Trying to pass in a boolean C# variable to a javascript variable and set it to true

C#Javascript

C# Problem Overview


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

C# Solutions


Solution 1 - C#

Try this:

myjavascript( <%= MyBooleanVariableInCSharp.ToString().ToLower() %> );

Solution 2 - C#

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' );

Solution 3 - C#

You could also do this.

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

Solution 4 - C#

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

myjavascript( @MyBooleanVariableInCSharp.ToString().ToLower() );

Solution 5 - C#

function toBool(s){ 
   return s==="True";
}

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmrblahView Question on Stackoverflow
Solution 1 - C#Andrew HareView Answer on Stackoverflow
Solution 2 - C#mendelView Answer on Stackoverflow
Solution 3 - C#Chris HawkesView Answer on Stackoverflow
Solution 4 - C#Hakan FıstıkView Answer on Stackoverflow
Solution 5 - C#Péter TajtiView Answer on Stackoverflow