1

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, '"'));
}
asked Mar 1, 2014 at 23:26
3
  • In your view try var data = @Html.Raw(Json.Encode(@Model.JSONDict)) Commented Mar 1, 2014 at 23:42
  • Ok, I post an answer then. If it works and if you want you may accept it. Happy coding :) Commented Mar 2, 2014 at 0:25
  • as the answer works for you (@aoakeson), please accept it as answer as it'll be helpful for others also. Commented Mar 2, 2014 at 11:26

1 Answer 1

2

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.

answered Mar 2, 2014 at 0:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.