I am struggling with understanding how to effectively utilize JSON objects within MVC and the correct way to pass them from Controller, to View, to Jscript.
I am also unsure if I am correctly parsing the JSON objects at the appropriate places...
Within my controller, I am returning a PartialView that contains 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);
}
In my View, I make this data accessible to my scripts by creating the following variable:
@model string
...
var mvcListOfVariablesInDB = '@Html.Raw(Json.Encode(Model))';
Subsequently, in my Javascript file, I try to retrieve and extract information and key value pairs from the data, but it appears to interpret the JSON as a string:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
for (var variable in variableList) {
alert(variableList[variable]);
}
Instead of retrieving key values of the JSON object, all I receive are alerts containing characters such as "
, [
, {
, etc., as each character of the string is displayed. How can I properly access the key values?
I have attempted modifying my JS code to use:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
However, doing so leads to an
Uncaught SyntaxError: Unexpected token I
error in my browser (likely when encountering the "I" of "Id).
Any assistance would be greatly appreciated. Thank you.