How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call?
Asked
Active
Viewed 1,841 times
5 Answers
24
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
- 779
- 5
- 11
-
How would you pass parameters to the MyAction? – Picflight Jul 09 '09 at 17:23
-
No formatting in a comment, but... $.getJSON("/controllerName/MyAction", { id: 7 }, callbackFunction); – BenB Oct 27 '09 at 13:29
10
Depending on your syntax preferences, the following also works:
public ActionResult MyAction()
{
return Json(new {Data = myObject});
}

John Sheehan
- 77,456
- 30
- 160
- 194

Matt
- 41,216
- 30
- 109
- 147
2
This is the Small block of code for just understand , how we can use JsonResults in MVC Controllers.
public JsonResult ASD()
{
string aaa = "Hi There is a sample Json";
return Json(aaa);
}

Thisara Subath
- 635
- 6
- 16
1
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) {
}
});

Stephen Rauch
- 47,830
- 31
- 106
- 135

Oshada Ekanayake
- 360
- 1
- 2
- 12
0
If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet.
public JsonResult Foo()
{
return Json("Secrets", JsonRequestBehavior.AllowGet);
}

Md Nazmoon Noor
- 3,187
- 1
- 24
- 30