Boolean FunctionThe Boolean() will return true for any non-empty, non-zero, object, or array. If the first parameter is 0, -0, null, false, NaN, undefined, '' (empty string), or no parameter passed then the Boolean() function returns false . The new operator with the Boolean() function returns a Boolean object.
There's a Boolean type though, as are literals true and false . JS variables don't have a type in the sense that you can't declare a variable that will only hold integers or strings (as happens in some other languages), but the particular value held by the variable at any given time will always have a type.
You can't. Razor is a . NET assembly and doesn't run on JavaScript or in a browser. It's meant to be executed server-side.
In JavaScript, a boolean value is one that can either be TRUE or FALSE. If you need to know “yes” or “no” about something, then you would want to use the boolean function. It sounds extremely simple, but booleans are used all the time in JavaScript programming, and they are extremely useful.
You may also want to try:
isFollowing: '@(Model.IsFollowing)' === '@true'
and an ever better way is to use:
isFollowing: @Json.Encode(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)
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)
};
var myViewModel = {
isFollowing: '@(Model.IsFollowing)' == "True";
};
Why True
and not true
you ask... Good question:
Why does Boolean.ToString output "True" and not "true"
A solution which is easier to read would be to do this:
isFollowing: @(Model.IsFollowing ? "true" : "false")
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With