【问题标题】:Using Razor, how do I render a Boolean to a JavaScript variable?使用 Razor,如何将布尔值呈现为 JavaScript 变量?
【发布时间】:2013-01-05 02:18:08
【问题描述】:

如何将布尔值呈现给 cshtml 文件中的 JavaScript 变量?

目前这显示了一个语法错误:

<script type="text/javascript" >

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

【问题讨论】:

    标签: javascript asp.net-mvc razor


    【解决方案1】:
    var myViewModel = {
        isFollowing: '@(Model.IsFollowing)' == "True";
    };
    

    你问为什么True而不是true...好问题:
    Why does Boolean.ToString output "True" and not "true"

    【讨论】:

    • 不要质疑,@Model.IsFollowing的编码真的是有效的JS语法吗?或者它是否依赖于它会是因为它恰好是布尔值的事实?
    • @Model.IsFollowing 是剃刀语法,不是 js
    • @gahooa,不,不是,它是在服务器上用 Razor 引擎解析的。
    • @Nikos,然后试试:'@(Model.IsFollowing)'
    • @Nikos,您尝试运行它吗?很多时候这只是 Visual Studio 的问题,但运行得非常好。尝试运行它!
    【解决方案2】:

    JSON 布尔值必须为小写。

    因此,试试这个(并确保 nto 在行上有// 注释):

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

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

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

    【讨论】:

    • .ToString() 方法可能是最有效的方法。使用 '@Model.IsFollowing.ToString().ToLowerInvariant()' 必须更高效,更直接。
    • 使用该方法,字符串和降低绝对是我选择中最干净的,因为它在 javascript 中读起来很好。
    【解决方案3】:

    你也可以试试:

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

    还有一个更好的方法是使用:

    isFollowing: @Json.Encode(Model.IsFollowing)
    

    【讨论】:

    • @Json.Encode(Model.IsFollowing) 是最优雅的解决方案。谢谢!
    • 通常会使用一个以上的布尔值,在这种情况下,对整个模型进行编码会使事情变得更好且易于使用。例如: var model = @Html.Raw(Json.Encode(Model)); 然后你可以调用 model.IsFollowing (对不起,我不知道如何正确格式化注释代码)
    • 添加@using System.Web.Helpers完成代码。
    【解决方案4】:

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

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

    这将在客户端生成以下内容,将 1 转换为 true,将 0 转换为 false。

    isFollowing: !!(1)  -- or !!(0)
    

    【讨论】:

    • 小修正!!@(Model.IsFollowing ? 1 : 0) 效果很好
    【解决方案5】:

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

    isFollowing: @Json.Serialize(Model.IsFollowing)    
    

    【讨论】:

    • 感谢您提及 asp.net core!
    【解决方案6】:

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

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

    【讨论】:

      【解决方案7】:

      Defining a conversion operation 并添加 .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# 一起使用,因为这会使您的代码混乱。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-26
        • 2023-02-11
        相关资源
        最近更新 更多