Possible Duplicate:
using razor within javascript
我想将模型中的一个简单值放在 Razor 页面上,并将其用作 javascript 函数中的常量值。即
<script> var myValue = @Model.myRecord.Count();</script>
因此 myValue = 我模型中的记录数。我以 myRecord.Count 为例,它可以是我模型中的任何值。
这可能吗?
TIA
J
好的,我偶然发现了以下解决方案:
<script> var myValue = @(Model.myRecord.Count())</script>
只需放入额外的括号即可。
当然,只要确保对其进行正确编码即可。例如,您可以对整个模型本身进行 JSON 编码:
@model IEnumerable<MyViewModel>
<script type="text/javascript">
var model = @Html.Raw(Json.Encode(Model));
// at this stage the model javascript variable represents the JSON encoded
// value of your server side model so that you can access all it's properties:
alert(model.length);
</script>
或:
alert(model[2].Foo.Bar);
或其他。
但是如果你只关心模型中元素的数量(如果这个模型代表一个集合):
var count = @Html.Raw(Json.Encode(Model.Count()));
alert(count);