How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call?
+20
A:
From the controller you can just return a JsonResult:
public ActionResult MyAction()
{
... // Populate myObject
return new JsonResult{ Data = myObject };
}
The form of the Ajax call will depend on which library you're using, of course. Using jQuery it would be something like:
$.getJSON("/controllerName/MyAction", callbackFunction);
where the callbackFunction
takes a parameter which is the data from the XHR request.
David Bick
2008-09-19 11:47:35
How would you pass parameters to the MyAction?
Picflight
2009-07-09 17:23:18
No formatting in a comment, but... $.getJSON("/controllerName/MyAction", { id: 7 }, callbackFunction);
BenB
2009-10-27 13:29:06
+6
A:
Depending on your syntax preferences, the following also works:
public ActionResult MyAction()
{
return Json(new {Data = myObject});
}
Matt
2008-09-19 15:16:59