Using Razor, how do I render a Boolean to a JavaSc

2019-01-08 10:02发布

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

Presently this shows a syntax error:

<script type="text/javascript" >

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

5条回答
倾城 Initia
2楼-- · 2019-01-08 10:02

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

isFollowing: @Json.Serialize(Model.IsFollowing)    
查看更多
甜甜的少女心
3楼-- · 2019-01-08 10:03

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.

isFollowing: !!(1)  -- or !!(0)
查看更多
Animai°情兽
4楼-- · 2019-01-08 10:10

The JSON boolean must be lowercase.

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):

var myViewModel = {
    isFollowing: @XmlConvert.ToString(Model.IsFollowing)
};
查看更多
该账号已被封号
5楼-- · 2019-01-08 10:14
var myViewModel = {
    isFollowing: '@(Model.IsFollowing)' == "True";
};

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

查看更多
欢心
6楼-- · 2019-01-08 10:24

You may also want to try:

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

and an ever better way is to use:

isFollowing: @Json.Encode(Model.IsFollowing)
查看更多
登录 后发表回答