ASP.NET MVC ActionResult for Rendering JSON using JSON.NET
With the latest drop of the ASP.NET MVC framework, as I’ve mentioned earlier, controller actions now return an ActionResult object. Out of the box, you have the choice between the RenderViewResult, ActionRedirectResult, HttpRedirectResult and EmptyResult types to do different things (they’re fairly self-explanatory, no?). In the application I’m currently working on though, I have several actions which are supposed to only ever get called asynchronously from the client (using jQuery, a totally awesome JavaScript library – more on that some other time), and I want these actions to return a JSON string that can be easily consumed by the JavaScript callback handler. With the help of James Newton-Kings excellent JSON.Net library, all it took to get this working was to implement my own RenderJsonResult class:
/// <summary>
/// An action result that renders the given object using JSON to the response stream.
/// </summary>
public class RenderJsonResult : ActionResult
{
/// <summary>
/// The result object to render using JSON.
/// </summary>
public object Result { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ContentType = "application/json";
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(context.HttpContext.Response.Output, this.Result);
}
}
My controller actions can then use the anonymous object notation of C# 3.0 to render JSON output:
return new RenderJsonResult { Result = new {status = "ok", assignedId = newItem.Id} };
Awesomeness! 🙂
Comments
This post is also available in: English
5/1/2008 4:47:52 PM
Wow, that was really smooth! Will replace my preview 1 View rendering JSON with this way of doing it. Oneliners ftw!
Kenneth Solberg
9/25/2008 5:37:34 AM
Have you done anything where you are posting back complex types to your controllers?
i.e. suppose you want to post to /Employee/Create and the Create method takes an Employee object…
Thoughts?
Dave
Dave
9/25/2008 5:08:43 PM
@Dave, I don’t think it makes much sense to have action methods that take complex objects. I would probably instead have a method like EmployeeController.Create(string name, string address, … Check out my other article on ASP.NET MVC + jQuery and you’ll se an example of this. iridescence.no/…/…h-ASPNET-MVC-and-jQuery.aspx
Fredrik
12/8/2008 5:19:32 AM
Hi Fred,
In asp.net webforms I used James Newton-King’s Jayrock json serializer to send json objects to server side as .net objects. For e.g. I would send a json object to a JsonRpcHandler method with attribute JsonRpcMethod and it would accept it as an IDictionary. I will than play with it and send back a .net serializable object which would automatically be converted to json by the handler. This way the two way communication is json.
How will I achieve this in asp.net mvc?
Confession: I haven’t explored asp.net mvc a lot.
Rean
3/16/2009 12:01:51 PM
when i use you code,for example
public class ShiwbController : Controller
{
public ActionResult ShowJson()
{
var json = new User { Name = «author», Sex = «male» };
return new RenderJsonResult { Result = new { status = «ok», assignedId =123 } };
}
public ActionResult js()
{
return JavaScript(«var i=0;»);
}
}
public class RenderJsonResult : ActionResult
{
public object Result { set; get; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ContentType = «applicaion/json»;
Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Serialize(context.HttpContext.Response.Output, this.Result);
}
}
when i visit http://localhost/showjson ,there is a messagebox to let me download file «showjson»,and this is appear when i visit http://localhost/js , why not?
thank you
virus