Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  179] [ 3]  / answers: 1 / hits: 25153  / 16 Years ago, tue, march 17, 2009, 12:00:00

I am passing a boolean value to a javascript function in my .net mvc action page.



problem is, it is outputting the value True and javascript apparently only accepts 'true' (in lower case).



I don't want to hack the variable and make it a string and convert it to lower case in my action, but it looks like I have no choice?


More From » asp.net-mvc

 Answers
26

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. :)


[#99833] Thursday, March 12, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxh

Total Points: 137
Total Questions: 100
Total Answers: 103

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
maxh questions
Tue, May 18, 21, 00:00, 3 Years ago
Mon, Jan 4, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
;