15

How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call?

thatismatt
9,85210 gold badges45 silver badges56 bronze badges
asked Sep 19, 2008 at 11:20

5 Answers 5

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.

answered Sep 19, 2008 at 11:47
Sign up to request clarification or add additional context in comments.

2 Comments

How would you pass parameters to the MyAction?
No formatting in a comment, but... $.getJSON("/controllerName/MyAction", { id: 7 }, callbackFunction);
10

Depending on your syntax preferences, the following also works:

public ActionResult MyAction()
{
 return Json(new {Data = myObject});
}
John Sheehan
78.3k30 gold badges162 silver badges194 bronze badges
answered Sep 19, 2008 at 15:16

Comments

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);
 }
answered Aug 8, 2017 at 9:22

Comments

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
50.1k32 gold badges119 silver badges143 bronze badges
answered Jun 23, 2018 at 3:22

Comments

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);
}
answered Jun 4, 2014 at 6:05

Comments

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.