10

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.

2
  • 2
    YES IT IS POSSIBLE. Are you facing any errors ? Commented Sep 10, 2012 at 20:39
  • 1
    That code should work. What is the error? Commented Sep 10, 2012 at 20:40

2 Answers 2

17

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Solved my issue, i had to change Encode to Serialize : @Html.Raw(Json.Serialize(Model.data)), works perfect, thanks
This only works if you embed the JS into the .cshtml file, by the way. The answer could make that more clear.
4

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.

1 Comment

int's are probably ok but other datatypes will fail with it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.