JSON and ASP.NET MVC

Question!

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



Answers

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);
}
By : nnoor


Depending on your syntax preferences, the following also works:

public ActionResult MyAction()
{
    return Json(new {Data = myObject});
}
By : Matt


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.



This video can help you solving your question :)
By: admin