如何在 Javascript 中比较来自 C# Viewbag 的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12213732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:36:28  来源:igfitidea点击:

How can I compare a value from C# Viewbag in Javascript?

c#javascriptasp.net-mvc-3

提问by Mateusz Rogulski

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

我想比较Viewbagjavascript 中的布尔值。所以起初我试过这个:

if (@Viewbag.MyBoolValue)
    do_sth();

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

但是后来我在控制台中出现了错误,例如:(Value False/True is not declared不完全是)。

So I tried this:

所以我试过这个:

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

and in javascript:

在 javascript 中:

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

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

但它也不起作用。我怎样才能让它工作?任何帮助,将不胜感激。

回答by Rory McCrossan

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

假设 ViewBag 中的值是 javascript 可以理解的类型,那么您所拥有的应该可以工作。

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:

但是请注意,您的第一个示例很可能不起作用,因为布尔值在 javascript 中为小写,在 C# 中为大写。考虑到这一点,试试这个:

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

回答by Elnaz

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

or

或者

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

or

或者

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

回答by HatSoft

The below will create a javascript vailable with value from viewbag

下面将创建一个带有 viewbag 值的 javascript vailable

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

回答by VJAI

This will work.

这将起作用。

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

if (@myBool)
    do_sth(); 

回答by GODFATHER

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

Insted true 和 false 在您的控制器中使用 0 和 1,在剃刀页面的顶部

@{ 
    var isSomething= Viewbag.MyBoolValue;
}

Later down

后来下来

if (@isSomething== 0)