Reputation: 127
I had a mvc object as my model.
I need to stringfiy my model as a json object type - and then use it in js as i please.
i currently doing something like this
<script type="text/javascript">
$(function () {
var jsonData2 = '@Html.Raw(Json.Encode(Model))';
showBeginDate(jsonData2);
});
</script>
But when i try to acess a json property for exemple as jsonData2.BeginDate I keep getting undefined. jsonData2 is a json object - why can i "read" from it?
Regards
Upvotes: 0
Views: 944
Reputation:
@riteshmeher 's suggestion is correct
var text = '@Html.Raw(Json.Encode(Model))';
var obj = JSON.parse(text);
I don't know your model so I created a simple model with 2 attributes: Id and Name. In case that the model is a list, you can read it:
// Access to object in position 1
var result = obj[0].Id + " - " + obj[0].Name;
In other case, access right to the property.
var result = obj.Id + " - " + obj.Name;
For more info, check this post:
http://www.w3schools.com/js/js_properties.asp
http://www.w3schools.com/json/tryit.asp?filename=tryjson_parse
UPDATE
like @Stephen Muecke said, better this:
var obj = @Html.Raw(Json.Encode(Model));
var result = obj[0].Id + " - " + obj[0].Name;
thank @Craig for the corrections
Upvotes: 1