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! :)