first time using Asp.Net MVC here.
I have a model class defined with 3 properties and I would like to access this model from javascript code on the view.
The best I found was this page
It would allow me to do something like this:
<script>
var model = <%= Model.ToJson() %>
alert(model.Prop1);
</script>
Since this code is based on an article from 2007 I was wondering if there is a better way to do this.
Thanks!
Yes, that’s a very good way to achieve this. It uses
JavaScriptSerializerto serialize your model into a JSON object and ensure proper escaping.As an alternative if you are using AJAX you could directly have a controller action returning JSON:
and then using jquery consume this action: