How to get bool value from ViewBag on view?
Asked Answered
P

5

9

I am trying to receive bool values from 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). 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?

EDIT:

I need to get ViewBag value in javascript part.

Pascal answered 19/8, 2015 at 8:41 Comment(5)
show, how you set this variableTress
Use a viewmodel instead of a viewbag. it's a slight bit more overhead to set up since you need to define everything in a class, but will save your sanity in the long run. are you trying to use the variable in JS or in razor?Narcose
In js. In perspective yes, it will be changed to model, but right now, I need ViewBag.Pascal
Can't you just change var test = '@ViewBag.Test'; to var test = @ViewBag.Test; ?Mapping
#12214232Mozzarella
F
9

You could use unboxing:

var test = @((bool)(ViewBag.Test??false))

Condensed into single line, handles missing ViewBag element.
Null coalescing operator returns the value of ViewBag.Test or false if "Test" doesn't exist. Finally value is typecast.

Ferdy answered 26/3, 2019 at 0:23 Comment(1)
Please improve your answer by explaining what it adds to the existing answers.Cumbrous
S
7

In controller code is 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. So you can use:

if(test)
    alert('true');
else 
    alert('false')
Shrewd answered 19/8, 2015 at 9:0 Comment(0)
C
4

If your value is bool in controller then use cshtml page

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

Circumstantiality answered 23/4, 2016 at 5:39 Comment(0)
C
0

You simply need to remove quotes var test = @ViewBag.Test

Cassondra answered 19/8, 2015 at 8:54 Comment(0)
E
0

Only need:

<script>
   var test = '@ViewBag.Test';
   if(test)
       {console.log(test);}
   else
       {console.log(test);};
</script>
Evilminded answered 26/4, 2016 at 7:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.