Reputation: 13616
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?
Upvotes: 0
Views: 434
Reputation:
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);
}
Upvotes: 2