This project is read-only.

Improved JsonResult Tutorial

This tutorial aims to illustrate the usage of the JsonResult ActionResult and why you would want to use it instead of the JsonResult included in the System.Web.Mvc assembly. This improved JsonResult resides in the DigitallyCreated.Utilities.Mvc assembly.

The DigitallyCreated.Utilities.Mvc.JsonResult works in exactly the same way as the System.Web.Mvc.JsonResult, except it exposes one extra feature: the ability to pass JavaScriptConverters to the underlying JavaScriptSerializer that does the JSON serialisation.

This is especially useful when you want to serialise Entity Framework entity classes, because often you want to strip some of the Entity Framework plumbing properties and just serialise the scalar properties.

Here is an example of the use of DigitallyCreated.Utilities.Mvc.JsonResult.

[AcceptVerbs(HttpVerbs.Post)] //POST to avoid an AJAX security vulnerability:
public ActionResult AjaxGetPricingData(int int)
    Pricing pricing = _BusinessLayer.CalculatePricing(id);
    return new JsonResult { Data = pricing, CustomConverters = new JavaScriptConverter[] { new PricingJsConverter() } };

Don't forget to put the following up with your other using statements:

using JsonResult=DigitallyCreated.Utilities.Mvc.JsonResult;

You'll notice that we're passing the JsonResult an array of JavaScriptConverers via its CustomConverters property. This property is the only difference between the JsonResult and the System.Web.Mvc.JsonResult.

Last edited Mar 23, 2010 at 8:12 AM by dchambers, version 1


No comments yet.