Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - pass ViewData as boolean

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.

like image 205
BeCool Avatar asked Dec 01 '10 06:12

BeCool


2 Answers

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.

like image 108
Jan Avatar answered Oct 20 '22 21:10

Jan


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.

like image 43
Robert Groves Avatar answered Oct 20 '22 20:10

Robert Groves