我将具有默认值(Id = 0、CityId = null、IsPublished = false)的模型从 Controller 传递到 View :
public class MyModel
{
public int Id { get; set; }
public int? CityId { get; set; }
public bool IsPublished { get; set; }
}
在 View 中,我将模型中的值分配给 JavaScript 中的变量 - cityId 应该是 JavaScript 的 bool 类型,isPublished 应该是 javascript null 或 int 类型:
<script>
var cityId = @Model.CityId; // value: False
var isPublished = @Model.IsPublished; // value: ''
</script>
但我有错误:
- 对于 cityId:
未捕获的 ReferenceError:未定义 False
- 对于 isPublished:
未捕获的语法错误:意外的标记;
我应该做什么?
最佳答案
您可以使用Json.Encode方法将数据对象转换为 JavaScript 对象表示法 (JSON) 格式的字符串。
var settings = @Html.Raw(Json.Encode(Model))
然后就可以这样使用了
var cityId = settings.CityId;
var isPublished = settings.IsPublished;
关于jquery - 将 False 和 '' 分配给 c# 中的 javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38245585/