7

I want to compare a boolean value from the Viewbag in javascript. So at first I tried this:

if (@Viewbag.MyBoolValue)
    do_sth();

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

So I tried this:

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

and in javascript:

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

But it does not work too. How can I make it work? Any help would be appreciated.

4

5 に答える 5

25

What you have should work, assuming that the value from the ViewBag is of a type which javascript can understand.

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

var myBoolValue = @ViewBag.MyBoolValue.ToString().ToLower();
if (myBoolValue)
    do_sth();
于 2012-08-31T10:47:23.177 に答える
1

The below will create a javascript vailable with value from viewbag

<script>
    var myBoolInJs = @Viewbag.MyBoolValue;
    if(myBoolInJs == true)
     do_sth();
</script>
于 2012-08-31T10:47:34.143 に答える
1
var myBoolVal = @((ViewBag.MyBoolValue ?? false).ToString().ToLower());

or

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

or

 var myBoolVal = @(Json.Encode(ViewBag.MyBoolValue ?? false));
于 2017-04-08T05:50:27.257 に答える
0

This will work.

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

if (@myBool)
    do_sth(); 
于 2012-08-31T11:27:36.257 に答える
0

Insted true and false use 0 and 1 in your controller, on top of razor page

@{ 
    var isSomething= Viewbag.MyBoolValue;
}

Later down

if (@isSomething== 0)
于 2016-10-13T10:18:57.230 に答える