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.
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.
精彩评论