简体   繁体   English

如何从 ViewBag 中获取 bool 值?

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

I am trying to receive bool values from ViewBag.我正在尝试从 ViewBag 接收布尔值。

But the issue is that to receive value I am using:但问题是为了获得我正在使用的价值:

var test = '@ViewBag.Test'

In this way value will be 'True' or 'False' (string).这样,值将是'True''False' (字符串)。 Of cource I can use something like if (test == 'True') but, is there a way to get from ViewBag bool value dirrectly, or at least convert it?当然我可以使用类似if (test == 'True')但是,有没有办法直接从 ViewBag bool 值中获取,或者至少转换它?

EDIT:编辑:

I need to get ViewBag value in javascript part.我需要在 javascript 部分获取 ViewBag 值。

In controller code is ViewBag.Test = true;在控制器代码是ViewBag.Test = true;

In View code is在视图代码是

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

Now the data type of variable test is a bool.现在变量 test 的数据类型是 bool。 So you can use:所以你可以使用:

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

You could use unboxing:您可以使用拆箱:

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

This provides a default value (false) if Test does not exist in the ViewBag and typecasts the result.如果 ViewBag 中不存在 Test 并且对结果进行类型转换,则这将提供一个默认值 (false)。

If your value is bool in controller then use cshtml page如果您在控制器中的值为bool则使用 cshtml 页面

bool test='@ViewBag.Test';

As viewbag needs not casting I think when you assign your value in a bool variable it gives you bool value in your view(cshtml) page由于viewbag不需要强制转换,我认为当您在bool变量中分配您的值时,它会在您的 view(cshtml) 页面中为您提供bool

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

Only need:只需要:

<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