How do I use Razor values in a javascript function? [duplicate]

梦想与她 提交于 2020-01-22 12:08:09

问题


Possible Duplicate:
using razor within 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.

<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.

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.


回答1:


Sure, just make sure to properly encode it. For example you could JSON encode the entire model itself:

@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);



回答2:


Make sure this is in a Razor file:

<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.



来源:https://stackoverflow.com/questions/12359080/how-do-i-use-razor-values-in-a-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!