Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  116] [ 5]  / answers: 1 / hits: 26373  / 12 Years ago, mon, september 10, 2012, 12:00:00

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.


More From » asp.net-mvc

 Answers
27

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

[#83149] Saturday, September 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
george

Total Points: 2
Total Questions: 98
Total Answers: 105

Location: Equatorial Guinea
Member since Sun, Feb 14, 2021
3 Years ago
;