When passing boolean value from controller to the view using ViewData, how do I retrieve it as a boolean value in javascript? example:
Controller:
ViewData["login"] = true;
View
<script type="text/javascript">
var login = <%= (bool)ViewData["Login"] %>; /// this doesn't work, throw javascript error;
</script>
yeh surely i can do
<script type="text/javascript">
var login = '<%= ViewData["Login"] %>'; /// now login is a string 'True'
</script>
But i rather keep login object as a boolean rather a string if that's possible.
Just remove the single quotes.
<script type="text/javascript">
var login = <%= (bool)ViewData["Login"] ? "true" : "false" %>;
</script>
This will result in:
var login = true;
Which will be parsed as a boolean in the browser.
I believe you could do this:
<script type="text/javascript">
var login = new Boolean(<%= (bool)ViewData["Login"] ? "true" : "false" %>);
</script>
edit: actually the first way I had it wouldn't work. The true/false values passed to Boolean() must be lowercase for this to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With