使用 Razor,我该如何将 Boolean 渲染到 JavaScript 变量中?

182

我该如何在cshtml文件中将布尔值渲染到JavaScript变量中?

目前这样会显示语法错误:

<script type="text/javascript" >

    var myViewModel = {
        isFollowing: @Model.IsFollowing  // This is a C# bool
    };
</script>
7个回答

356

你可能也想尝试一下:

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

更好的方法是使用:

isFollowing: @Json.Encode(Model.IsFollowing)

71
我认为,@Json.Encode(Model.IsFollowing) 是最优雅的解决方案。谢谢! - Sandro
2
通常会使用多个布尔值,因此对整个模型进行编码可以使以后的使用变得简单明了。例如:var model = @Html.Raw(Json.Encode(Model)); 然后您只需调用 model.IsFollowing 即可(抱歉,我不知道如何正确格式化注释代码)。 - Jynn
2
@using System.Web.Helpers添加到代码中以完成。 - taylorswiftfan

78

因为搜索引导我到这里:在ASP.NET Core中,IJsonHelper没有Encode()方法,相反,应该使用Serialize()。例如:

isFollowing: @Json.Serialize(Model.IsFollowing)    

8
谢谢提到 asp.net core! - Sharif Mamun

31

JSON布尔值必须小写。

因此,请尝试以下内容(确保该行未添加//注释):

var myViewModel = {
    isFollowing: @Model.IsFollowing.ToString().ToLower()
};

或者(注:您需要使用命名空间 System.Xml):

var myViewModel = {
    isFollowing: @XmlConvert.ToString(Model.IsFollowing)
};

1
".ToString()方法可能是最有效的方法。使用'@Model.IsFollowing.ToString().ToLowerInvariant()'应该会更有效率并且更为直接。" - XDS
使用方法、toString和toLowerCase是我认为最干净的,因为在JavaScript中读起来很好。 - Frank Thomas

15

不是质疑,但 @Model.IsFollowing 的编码实际上是有效的JS语法吗?还是它依赖于它是布尔值这一事实呢? - gahooa
@Model.IsFollowing是Razor语法,不是JS。 - Nikos
@gahooa,不是的,它是在服务器上使用Razor引擎解析的。 - gdoron
@Nikos,请尝试:'@(Model.IsFollowing)' - gdoron
@Nikos,你试着运行了吗?很多时候只是Visual Studio的问题,但它可以完美运行。试着去运行它! - gdoron

11

一个更易读的解决方案是这样的:

isFollowing: @(Model.IsFollowing ? "true" : "false")

5

这里有另一个选项需要考虑,使用!!转换为布尔值。

isFollowing: !!(@Model.IsFollowing ? 1 : 0)

这将在客户端生成以下内容,其中1会被转换为true,0会被转换为false。
isFollowing: !!(1)  -- or !!(0)

小修正:!!@(Model.IsFollowing ? 1 : 0) 很好用。 - chicken

0

定义一个转换操作并添加一个 .ToString() 的重写可以省去很多工作。

在您的项目中定义这个struct

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

使用方法

您可以直接将 C# 的 bool 进行转换,就像这个问题的情况一样:

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

但是您也可以直接在 Razor 代码中使用 JSBool,并期望它会在不需要任何额外工作的情况下给出 truefalse

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

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

这能够工作是因为我们在上面定义的隐式转换运算符。

确保只在要在 Razor 代码中使用时才使用它。换句话说,不要在普通的 C# 中使用它,因为这会使您的代码混乱。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接