I pass JSON to the razor view page with help of ViewBag.
Here is the code in the action function:
public ActionResult GmailOAuthCallback(string code)
{
object contacts = GmailServiceWorkflow.GetContacts(code);
string json = new JavaScriptSerializer().Serialize(contacts);
ViewBag.name = json;
return View("SomeWindow");
}
At the razor view page I want to parse JSON to the object.
Here is the code in view razor page:
function myFunction() {
var arrObject = JSON.parse("@ViewBag.name");
alert(arrObject[0].firstName);
}
But I get this error:
SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data
Any idea why I get this error and how to fix it?
asked Nov 1, 2014 at 22:43
-
THe error states that the JSON-data is invalid. Your code has nothing to do with that.vrijdenker– vrijdenker2014年11月01日 22:45:42 +00:00Commented Nov 1, 2014 at 22:45
1 Answer 1
Rather than using JavaScriptSerializer
, you ca acheive this by passing the collection to the view
public ActionResult GmailOAuthCallback(string code)
{
object contacts = GmailServiceWorkflow.GetContacts(code);
ViewBag.name = contacts ;
return View("SomeWindow");
}
then in the script
function myFunction() {
var arrObject = JSON.parse('@Html.Raw(Json.Encode(ViewBag.name))');
alert(arrObject[0].firstName);
}
answered Nov 1, 2014 at 23:10
user3559349user3559349
5 Comments
Michael
Stephen thanks for the answer but I get red line(error) under Json.
Tieson T.
@Michael That just means you need to include the relevant namespace, System.Web.Helpers, and either add a using statement and/or add the System.Web.Helpers to the web.config (as Stephen notes).
Michael
Yes,I know I already have @using System.Web.Helpers ,but steal I get the error
Explore related questions
See similar questions with these tags.
default