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.

Olegs Jasjko
  • 2,128
  • 6
  • 27
  • 47
  • show, how you set this variable – Backs Aug 19 '15 at 08:43
  • 1
    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? – user1666620 Aug 19 '15 at 08:45
  • In js. In perspective yes, it will be changed to model, but right now, I need ViewBag. – Olegs Jasjko Aug 19 '15 at 08:49
  • Can't you just change `var test = '@ViewBag.Test';` to `var test = @ViewBag.Test;` ? – Fabjan Aug 19 '15 at 09:06
  • http://stackoverflow.com/questions/12213732/how-can-i-compare-a-value-from-c-sharp-viewbag-in-javascript – Elnaz Apr 08 '17 at 05:42

5 Answers5

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.

Leigh.D
  • 463
  • 5
  • 13
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')
shox
  • 677
  • 1
  • 5
  • 19
J Santosh
  • 3,808
  • 2
  • 22
  • 43
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

Dr.jacky
  • 3,341
  • 6
  • 53
  • 91
0

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

Troopers
  • 5,127
  • 1
  • 37
  • 64
0

Only need:

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