我该如何在cshtml文件中将布尔值渲染到JavaScript变量中?
目前这样会显示语法错误:
<script type="text/javascript" >
var myViewModel = {
isFollowing: @Model.IsFollowing // This is a C# bool
};
</script>
我该如何在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)
因为搜索引导我到这里:在ASP.NET Core中,IJsonHelper
没有Encode()
方法,相反,应该使用Serialize()
。例如:
isFollowing: @Json.Serialize(Model.IsFollowing)
JSON布尔值必须小写。
因此,请尝试以下内容(确保该行未添加//
注释):
var myViewModel = {
isFollowing: @Model.IsFollowing.ToString().ToLower()
};
或者(注:您需要使用命名空间 System.Xml
):
var myViewModel = {
isFollowing: @XmlConvert.ToString(Model.IsFollowing)
};
var myViewModel = {
isFollowing: '@(Model.IsFollowing)' == "True";
};
你问为什么是 True
而不是 true
... 好问题:
为什么 Boolean.ToString 输出 "True" 而不是 "true"
@Model.IsFollowing
的编码实际上是有效的JS语法吗?还是它依赖于它是布尔值这一事实呢? - gahooa'@(Model.IsFollowing)'
- gdoron一个更易读的解决方案是这样的:
isFollowing: @(Model.IsFollowing ? "true" : "false")
这里有另一个选项需要考虑,使用!!转换为布尔值。
isFollowing: !!(@Model.IsFollowing ? 1 : 0)
isFollowing: !!(1) -- or !!(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
,并期望它会在不需要任何额外工作的情况下给出 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# 中使用它,因为这会使您的代码混乱。
@Json.Encode(Model.IsFollowing)
是最优雅的解决方案。谢谢! - Sandro@using System.Web.Helpers
添加到代码中以完成。 - taylorswiftfan