[英]Using Razor, how do I render a Boolean to a JavaScript variable?
如何在 cshtml 文件中将布尔值呈现给 JavaScript 变量?
目前这显示了一个语法错误:
<script type="text/javascript" >
var myViewModel = {
isFollowing: @Model.IsFollowing // This is a C# bool
};
</script>
您可能还想尝试:
isFollowing: '@(Model.IsFollowing)' === '@true'
更好的方法是使用:
isFollowing: @Json.Encode(Model.IsFollowing)
JSON布尔值必须为小写。
因此,请尝试以下操作(并确保nto在行上添加//
注释):
var myViewModel = {
isFollowing: @Model.IsFollowing.ToString().ToLower()
};
或(注意:您需要使用名称空间System.Xml
):
var myViewModel = {
isFollowing: @XmlConvert.ToString(Model.IsFollowing)
};
因为搜索将我带到了这里:在ASP.NET Core中, IJsonHelper
没有Encode()
方法。 而是使用Serialize()
。 例如:
isFollowing: @Json.Serialize(Model.IsFollowing)
var myViewModel = {
isFollowing: '@(Model.IsFollowing)' == "True";
};
您问为什么为True
而不是true
...好问题:
为什么Boolean.ToString输出“ True”而不是“ true”
这是另一个可以考虑的选择,使用!! 转换为布尔值。
isFollowing: !!(@Model.IsFollowing ? 1 : 0)
这将在客户端生成以下内容,其中1转换为true,0转换为false。
isFollowing: !!(1) -- or !!(0)
一个更容易阅读的解决方案是这样做:
isFollowing: @(Model.IsFollowing ? "true" : "false")
定义转换操作并添加.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)
}
但你也可以使用一个JSBool
在剃刀代码直接与期望,它将使true
和false
,而无需做任何额外的工作:
@{
JSBool isA = true;
JSBool isB = false;
// Standard boolean operations work too:
JSBool isC = a || b;
}
<script>
if (@isC)
console.log('true');
</script>
这是因为我们在上面定义的隐式转换运算符。
请确保仅在您打算在 Razor 代码中使用它时才使用它。 换句话说,不要将它与普通的 C# 一起使用,因为这会使您的代码变得混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.