I’m confused as to how I should be using JSON objects within MVC and how they should passed from Controller, to View, to Jscript.
I’m also not sure if I’m correctly parsing the JSON objects at the right points…
My controller is returning a PartialView with a json object (“Variables” is a list of data e.g. Id=2012, Name=BillyJoel, Value=”£2,000″):
public ActionResult JavascriptConstants() {
var variables = Service.Obtain<VariableService>().All().ToList();
var json = new JavaScriptSerializer().Serialize(variables);
return PartialView("JavascriptConstants", json);
}
My View then makes this data available to my scripts by creating this variable:
@model string
...
var mvcListOfVariablesInDB = '@Html.Raw(Json.Encode(Model))';
My Jscript file then accesses the data and attempts to pull out the information and key value pairs, but seems to be interpreting the JSON as a string:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
for (var variable in variableList) {
alert(variableList[variable]);
}
This just returns alerts of ", [, {, etc. as each character of the string is displayed. How do I access the key values of the JSON object?
I’ve tried changing my JS to use:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
But this just gives me an Uncaught SyntaxError: Unexpected token I error in my browser (I’m assuming when it hits the “I” of “Id).
Any help much appreciated, thanks.
I found the issue:
The issue was the use of
JavaScriptSerializer().Serialize(foo)as this was creating a JSON object that contained newlines and tabs instead of replacing them with\nand\t.$.parseJSON()cannot handle newlines and so throws up unexpected token error.This was corrected by importing the
JSON.NETpackage and using :This passed a JSON object with newlines and tabs replaced with
\n‘s and\t‘s. Which can then be made accessible to the View using:and finally in the script using:
Hope this helps someone else one day…