javascript MVC - 将 ViewData 作为布尔值传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4321694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC - pass ViewData as boolean
提问by BeCool
When passing boolean value from controller to the view using ViewData, how do I retrieve it as a boolean value in javascript? example:
使用 ViewData 将布尔值从控制器传递到视图时,如何在 javascript 中将其检索为布尔值?例子:
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.
但如果可能的话,我宁愿将登录对象保留为布尔值而不是字符串。
采纳答案by Jan
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.
这将在浏览器中被解析为一个布尔值。
回答by Robert Groves
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.
编辑:实际上我的第一种方法是行不通的。传递给 Boolean() 的真/假值必须是小写的,这样才能工作。

