使用 Razor,如何将布尔值呈现为 JavaScript 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14448604/
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-08-24 16:48:42  来源:igfitidea点击:

Using Razor, how do I render a Boolean to a JavaScript variable?

javascriptasp.net-mvcrazor

提问by Nikos

How do I render a Boolean to a JavaScript variable in a cshtml file?

如何在 cshtml 文件中将布尔值呈现给 JavaScript 变量?

Presently this shows a syntax error:

目前这显示了一个语法错误:

<script type="text/javascript" >

    var myViewModel = {
        isFollowing: @Model.IsFollowing  // This is a C# bool
    };
</script>

回答by another_user

You may also want to try:

您可能还想尝试:

isFollowing: '@(Model.IsFollowing)' === '@true'

and an ever better way is to use:

更好的方法是使用:

isFollowing: @Json.Encode(Model.IsFollowing)

回答by Lucero

The JSON boolean must be lowercase.

JSON 布尔值必须为小写。

Therefore, try this (and make sure nto to have the //comment on the line):

因此,试试这个(并确保没有//注释就行了):

var myViewModel = {
    isFollowing: @Model.IsFollowing.ToString().ToLower()
};

Or (note: you need to use the namespace System.Xml):

或者(注意:您需要使用命名空间System.Xml):

var myViewModel = {
    isFollowing: @XmlConvert.ToString(Model.IsFollowing)
};

回答by Marc L.

Because a search brought me here: in ASP.NET Core, IJsonHelperdoesn't have an Encode()method. Instead, use Serialize(). E.g.:

因为搜索将我带到这里:在 ASP.NET Core 中,IJsonHelper没有Encode()方法。相反,使用Serialize(). 例如:

isFollowing: @Json.Serialize(Model.IsFollowing)    

回答by gdoron is supporting Monica

var myViewModel = {
    isFollowing: '@(Model.IsFollowing)' == "True";
};

Why Trueand not trueyou ask... Good question:
Why does Boolean.ToString output "True" and not "true"

为什么True而不是true你问......好问题:
为什么 Boolean.ToString 输出“真”而不是“真”

回答by Stuart Hallows

Here's another option to consider, using the !! conversion to boolean.

这是另一个需要考虑的选项,使用 !! 转换为布尔值。

isFollowing: !!(@Model.IsFollowing ? 1 : 0)

This will generate the following on the client side, with 1 being converted to true and 0 to false.

这将在客户端生成以下内容,1 转换为 true,0 转换为 false。

isFollowing: !!(1)  -- or !!(0)

回答by marxlaml

A solution which is easier to read would be to do this:

一个更容易阅读的解决方案是这样做:

isFollowing: @(Model.IsFollowing ? "true" : "false")