繁体   English   中英

如何从 ViewBag 中获取 bool 值?

[英]How to get bool value from ViewBag on view?

我正在尝试从 ViewBag 接收布尔值。

但问题是为了获得我正在使用的价值:

var test = '@ViewBag.Test'

这样,值将是'True''False' (字符串)。 当然我可以使用类似if (test == 'True')但是,有没有办法直接从 ViewBag bool 值中获取,或者至少转换它?

编辑:

我需要在 javascript 部分获取 ViewBag 值。

在控制器代码是ViewBag.Test = true;

在视图代码是

var test=@(ViewBag.Test.ToString().ToLower());
console.log(test);

现在变量 test 的数据类型是 bool。 所以你可以使用:

if(test)
    alert('true');
else 
    alert('false')

您可以使用拆箱:

@((bool)(ViewBag.Test??false))

如果 ViewBag 中不存在 Test 并且对结果进行类型转换,则这将提供一个默认值 (false)。

如果您在控制器中的值为bool则使用 cshtml 页面

bool test='@ViewBag.Test';

由于viewbag不需要强制转换,我认为当您在bool变量中分配您的值时,它会在您的 view(cshtml) 页面中为您提供bool

您只需要删除引号var test = @ViewBag.Test

只需要:

<script>
   var test = '@ViewBag.Test';
   if(test)
       {console.log(test);}
   else
       {console.log(test);};
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM