How can I compare a value from C# Viewbag in Javas

2019-04-28 15:38发布

问题:

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.

回答1:

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();


回答2:

The below will create a javascript vailable with value from viewbag

<script>
    var myBoolInJs = @Viewbag.MyBoolValue;
    if(myBoolInJs == true)
     do_sth();
</script>


回答3:

This will work.

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

if (@myBool)
    do_sth(); 


回答4:

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)


回答5:

var myBoolVal = @((ViewBag.MyBoolValue ?? false).ToString().ToLower());

or

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

or

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