How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call?
5 Answers
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.
You can also System.Web.Script.Serialization; as below
using System.Web.Script.Serialization;
public ActionResult MyAction(string myParam)
{
return new JavaScriptSerializer().Serialize(myObject);
}
Ajax
$.ajax({
type: 'POST',
url: '@Url.Action("MyAction","MyMethod")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "myParam": "your data" }),
success: function(data)
{
console.log(data)
},
error: function (request, status, error) {
}
});