In my application I am calling an action method from JavaScript & expecting result as JSON. This is pretty simple in ASP.NET MVC, Once we get response object in action method we can call Json() method pass response object as a parameter, then it will transform your response object as JSON & return it as JsonResult.
Here is my product model:
namespace ReturningJsonSample.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public string Category { get; set; } } }
ProductController:
using ReturningJsonSample.Models; using System.Collections.Generic; using System.Web.Mvc; namespace ReturningJsonSample.Controllers { public class ProductController : Controller { [HttpPost] public JsonResult GetProducts() { var products = new List<Product> { new Product { Id=1, Name="EOS 1100D", Price =29990, Category="Cameras" }, new Product { Id=6, Name="REST in Practice", Category="Books" }, new Product { Id=8, Name="Lumia 900", Price =35487, Category="SmartPhones" } }; return Json(products); } } }
Here is the Json response:
[ {"Id":1,"Name":"EOS 1100D","Price":29990,"Category":"Cameras"}, {"Id":6,"Name":"REST in Practice","Price":0,"Category":"Books"}, {"Id":8,"Name":"Lumia 900","Price":35487,"Category":"SmartPhones"} ]
Few important point to observe, GetProducts() action method is annotated with [HttpPost] attribute. Let’s try the same sample by removing [HttpPost] attribute on GetProducts() action method.
The error message is pretty clear that we can not request for JSON via Http Get request, this not allowed for various security reasons. But if we have a requirement to return JSON for a Http Get request, we can use Json() method with JsonRequestBehavior.AllowGet parameter.
return Json(products,JsonRequestBehavior.AllowGet);