Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you pass a boolean value in JavaScript?

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.

How do you declare a boolean variable in JavaScript?

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.

Can you use Razor syntax in JavaScript?

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.

Can we use boolean in JavaScript?

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)