I am unable to understand why my JSON is not parsing correctly. I am parsing a c# dictionary to a JSON string in my controller. The output is correct there. When I pass the string back to my partial view, it does not render properly, and I am getting "Unexpected Token &" Ive tried it multilple ways in returning it to the view, but to no avail.
View:
var data = @Model.JSONDict
//data output - var data = {"3/1/2014":2,"2/28/2014":1,"2/27/2014":1,"2/26/2014":0,"2/25/2014":0,"2/24/2014":0,"2/23/2014":0}
//var keys = Object.keys(data);
Controller:
string output = JsonConvert.SerializeObject(dict);
//Resulting Output = "{\"3/1/2014\":2,\"2/28/2014\":1,\"2/27/2014\":1,\"2/26/2014\":0,\"2/25/2014\":0,\"2/24/2014\":0,\"2/23/2014\":0}"
ViewData["allEntries"] = output;
model.JSONDict = output;
return PartialView("_Graph", model);
I have also tried parsing out the & acocording to this post: Cannot get data in a view after parsing json data from controller in asp.net mvc like so, but getting the same error message:
storejson= getJSonObject("@ViewBag.JsonData");
function getJSonObject(value) {
return $.parseJSON(value.replace(/"/ig, '"'));
}
1 Answer 1
The problem is that in the output the JSON is encoded. In order to deal with this you can use the @Html.Raw()
like so :
var data = @Html.Raw(Json.Encode(@Model.JSONDict))
But be advised that using @Html.Raw()
may cause some security issues so it must be used with caution.
var data = @Html.Raw(Json.Encode(@Model.JSONDict))
accept
it as answer as it'll be helpful for others also.