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

2019-01-08 10:20发布

问题:

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>

回答1:

You may also want to try:

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

and an ever better way is to use:

isFollowing: @Json.Encode(Model.IsFollowing)


回答2:

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


回答3:

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)    


回答4:

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

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



回答5:

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)