MVC - pass ViewData as logical

Sorry for the newbie question.

When passing a boolean value from a controller to a view using ViewData, how do I get it as a boolean 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>

Of course i can do

  <script type="text/javascript">
var login = '<%= ViewData["Login"] %>';   /// now login is a string 'True'
</script>

But I rather save the input object as a boolean, and a string if possible

Thank!

+5
source share
2 answers

Just remove the single quotes.

<script type="text/javascript">
    var login = <%= (bool)ViewData["Login"] ? "true" : "false" %>;
</script>

This will lead to:

var login = true;

which will be parsed as boolean in the browser.

+5
source

I think you could do this:

<script type="text/javascript"> 
    var login = new Boolean(<%= (bool)ViewData["Login"] ? "true" : "false" %>);
</script> 

edit: , , . true/false, Boolean(), , .

0

All Articles