ASP.NET MVC ActionResult for Rendering JSON using JSON.NET

ASP.NET MVC ActionResult for Rendering JSON using JSON.NET

ASP.NET MVC ActionResult for Rendering JSON using JSON.NET

ASP.NET MVC ActionResult for Rendering JSON using JSON.NET

Author: Fredrik Kalseth
An entry about asp.net mvc | ajax Publication date 1. May 2008 18:03
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! 🙂
Currently rated 4.3 by 7 people
  • Currently 4.285714/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

5/1/2008 4:47:52 PM

Kenneth Solberg

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

Dave

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 United States

9/25/2008 5:08:43 PM

Fredrik

@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 Norway

12/8/2008 5:19:32 AM

Rean

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 India

3/16/2009 12:01:51 PM

virus

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 People's Republic of China

This post is also available in: Norsk bokmål