How can I compare the value with C # Viewbag in Javascript?

I want to compare boolean value from Viewbagin javascript. So first I tried this:

if (@Viewbag.MyBoolValue)
    do_sth();

But then I have an error in the console like: Value False/True is not declared(not really).

So, I tried this:

@{
    string myBool = ((bool)Viewbag.MyBoolValue) ? "true" : "false";
}

and in javascript:

if (@myBool == "true")
    do_sth();

But that doesn't work either. How can I make it work? Any help would be appreciated.

+6
source share
5 answers

What you have should work if you assume that the value from the ViewBag is of a type that javascript understands.

Please note, however, that your first example most likely did not work, because booleans are lowercase in javascript and uppercase in C #. With that in mind, try this:

var myBoolValue = @ViewBag.MyBoolValue.ToString().ToLower();
if (myBoolValue)
    do_sth();
+18

javascript vailable viewbag

<script>
    var myBoolInJs = @Viewbag.MyBoolValue;
    if(myBoolInJs == true)
     do_sth();
</script>
+1
var myBoolVal = @((ViewBag.MyBoolValue ?? false).ToString().ToLower());

var myBoolVal = '@(ViewBag.MyBoolValue)'==='@true';

 var myBoolVal = @(Json.Encode(ViewBag.MyBoolValue ?? false));
+1

.

@{     
   string myBool = Viewbag.MyBoolValue.ToString().ToLower(); 
}

if (@myBool)
    do_sth(); 
0
source

True and false usage of 0 and 1 is set in your controller, on top of the razor page

@{ 
    var isSomething= Viewbag.MyBoolValue;
}

Later down

if (@isSomething== 0)
0
source

All Articles