How to use Razor values ​​in javascript function?

Possible duplicate:
using a razor in javascript

I would like to put the siimple value from the model on the 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 number of records in my model. I use myRecord.Count as an example, it can be any value from my model.

Is it possible?

TIA J

OK I came across the following solution:

<script> var myValue = @(Model.myRecord.Count())</script>

Just adding extra brackets helped.

+5
source share
2 answers

Of course, just make sure it is encoded correctly. For example, you can JSON encode the whole model:

@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 properties:
    alert(model.length);
</script>

or

alert(model[2].Foo.Bar);

or something else.

( ):

var count = @Html.Raw(Json.Encode(Model.Count()));
alert(count);
+8

, Razor:

<script> var myValue = @Model.myRecord.Count();</script>

js, Razor .

+2

All Articles