0

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
1
  • THe error states that the JSON-data is invalid. Your code has nothing to do with that. Commented Nov 1, 2014 at 22:45

1 Answer 1

2

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

5 Comments

Stephen thanks for the answer but I get red line(error) under Json.
What does the error indicate? You may be missing <add namespace="System.Web.Helpers" /> from your web.config file
@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).
Yes,I know I already have @using System.Web.Helpers ,but steal I get the error
Strange, works for me. The script is not in a external file is it?

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.