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>
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>
You may also want to try:
isFollowing: '@(Model.IsFollowing)' === '@true'
and an ever better way is to use:
isFollowing: @Json.Encode(Model.IsFollowing)
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)
};
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)
var myViewModel = {
isFollowing: '@(Model.IsFollowing)' == "True";
};
Why True
and not true
you ask... Good question:
Why does Boolean.ToString output "True" and not "true"
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)