182

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>
Mafii
  • 7,227
  • 1
  • 35
  • 55
Nikos
  • 7,295
  • 7
  • 52
  • 88

7 Answers7

356

You may also want to try:

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

and an ever better way is to use:

isFollowing: @Json.Encode(Model.IsFollowing)
another_user
  • 3,590
  • 2
  • 12
  • 7
  • 71
    `@Json.Encode(Model.IsFollowing)` is imho the most elegant solution. Thank you! – Sandro Apr 16 '14 at 14:42
  • 2
    Normally there's going to be more than one boolean being used in which case encoding the whole model makes things nice and easy to use thereafter. eg: **var model = @Html.Raw(Json.Encode(Model));** and then you can just call *model.IsFollowing* (Sorry I don't know how to format the comment code properly) – Jynn Apr 13 '17 at 09:06
  • 2
    Add `@using System.Web.Helpers` to complete the code. – taylorswiftfan Apr 21 '20 at 19:11
77

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)    
Marc L.
  • 3,296
  • 1
  • 32
  • 42
31

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)
};
Lucero
  • 59,176
  • 9
  • 122
  • 152
  • 1
    The .ToString() approach is probably the most efficient one. Using '@Model.IsFollowing.ToString().ToLowerInvariant()' must be a bit more efficient and somewhat more straightforward. – XDS Feb 06 '17 at 08:44
  • Using the method, to string and to lower is definitely the cleanest in my option as it reads nicely in javascript. – Frank Thomas Apr 20 '20 at 15:13
15
var myViewModel = {
    isFollowing: '@(Model.IsFollowing)' == "True";
};

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

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367
10

A solution which is easier to read would be to do this:

isFollowing: @(Model.IsFollowing ? "true" : "false")
marxlaml
  • 321
  • 2
  • 11
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)
Stuart Hallows
  • 8,795
  • 5
  • 45
  • 57
0

Defining a conversion operation and adding an override of .ToString() can save a lot of work.

Define this struct in your project:

/// <summary>
/// A <see cref="bool"/> made for use in creating Razor pages.
/// When converted to a string, it returns "true" or "false".
/// </summary>
public struct JSBool
{
    private readonly bool _Data;

    /// <summary>
    /// While this creates a new JSBool, you can also implicitly convert between the two.
    /// </summary>
    public JSBool(bool b)
    {
        _Data = b;
    }

    public static implicit operator bool(JSBool j) => j._Data;
    public static implicit operator JSBool(bool b) => new JSBool(b);

    // Returns "true" or "false" as you would expect
    public override string ToString() => _Data.ToString().ToLowerInvariant();
}

Usage

You can directly cast a C# bool, as in the case of the question:

{
    // Results in `isFollowing : true`
    isFollowing : @((JSBool)Model.IsFollowing)
}

But you can also use a JSBool directly in the Razor code with the expectation that it will give true and false without having to do any extra work:

@{
    JSBool isA = true;
    JSBool isB = false;
    // Standard boolean operations work too:
    JSBool isC = a || b;
}

<script>
    if (@isC)
        console.log('true');
</script>

This works because of the implicit conversion operators we defined above.


Just make sure to only ever use this when you intend to use it in Razor code. In other words, don't use it with normal C# as this can make your code messy.

General Grievance
  • 4,555
  • 31
  • 31
  • 45