如何在 javascript 函数中使用 Razor 值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12359080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use Razor values in a javascript function?
提问by John S
Possible Duplicate:
using razor within javascript
可能重复:
在 javascript 中使用剃刀
I would like to place a siimple value from the model on a razor page and use it as a constant value in a javascript function. i.e.
我想将模型中的简单值放在剃刀页面上,并将其用作 javascript 函数中的常量值。IE
<script> var myValue = @Model.myRecord.Count();</script>
so that myValue = the record count in my model. I am using myRecord.Count as an example, it could be any value from my model.
这样 myValue = 我模型中的记录数。我以 myRecord.Count 为例,它可以是我模型中的任何值。
Is this possible?
这可能吗?
TIA J
蒂亚杰
OK I stumbled across the following solution:
好的,我偶然发现了以下解决方案:
<script> var myValue = @(Model.myRecord.Count())</script>
Just putting inthe extra brackets helped.
只需放入额外的括号就有所帮助。
回答by Darin Dimitrov
Sure, just make sure to properly encode it. For example you could JSON encode the entire model itself:
当然,只要确保正确编码即可。例如,您可以对整个模型本身进行 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>
or:
或者:
alert(model[2].Foo.Bar);
or whatever.
管他呢。
But if you only care about the number of elements inside the model (if this model represents a collection):
但是如果你只关心模型中元素的数量(如果这个模型代表一个集合):
var count = @Html.Raw(Json.Encode(Model.Count()));
alert(count);
回答by Gromer
Make sure this is in a Razor file:
确保这是在 Razor 文件中:
<script> var myValue = @Model.myRecord.Count();</script>
If it is in just a js file, the Razor engine won't run that code at all.
如果它只是在一个 js 文件中,则 Razor 引擎根本不会运行该代码。