Large JSON Result for Telerik’s MVC Grid

By | September 27, 2011

You might have encountered this error “Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.” when pushing a large data to Telerik’s MVC Grid.


My best guess is you have tried solutions to update the web.config to contain sections something similar to below.

<configuration> 
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="2147483644"/>
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration>

Well that wont work because the value of the MaxJsonLength only applies to the internal JavaScriptSerializer that is used by the asynchronous communication layer to invoke Web services methods. The solution is simple we just need to return a Large Json Result for the MVC Grid.

So lets say you Initially have a method called SelectSomethingAjax, you usually return it as ActionResult

[GridAction]
public ActionResult SelectInvoiceAjax()
{
    var model = GetRecords();

    return View(new GridModel<YourViewModel>
    {
        Data = model.YourViewModel
    });
}

Instead of doing that you should implement your own ActionResult that will output a JSON result where you can modify the properties of the JavaScriptSerializer. So with the help of this post (http://brianreiter.org/2011/01/03/custom-jsonresult-class-for-asp-net-mvc-to-avoid-maxjsonlength-exceeded-exception/) which I found here (http://www.java2s.com/Open-Source/ASP.NET/AJAX/ajaxmapdataconnector/DataConDemoWebRole/Business/LargeJsonResult.cs.htm) we have an implementation of the LargeJsonResult.
(Below is copied on his blog site)

using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

public class LargeJsonResult : JsonResult
{
    const string JsonRequest_GetNotAllowed = "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.";
    public LargeJsonResult()
    {
        MaxJsonLength = 1024000;
        RecursionLimit = 100;
    }

    public int MaxJsonLength { getset; }
    public int RecursionLimit { getset; }

    public override void ExecuteResult( ControllerContext context )
    {
        if( context == null )
        {
            throw new ArgumentNullException"context" );
        }
        if( JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
            String.Equals( context.HttpContext.Request.HttpMethod, "GET"StringComparison.OrdinalIgnoreCase ) )
        {
            throw new InvalidOperationException( JsonRequest_GetNotAllowed );
        }

        HttpResponseBase response = context.HttpContext.Response;

        if( !String.IsNullOrEmpty( ContentType ) )
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if( ContentEncoding != null )
        {
            response.ContentEncoding = ContentEncoding;
        }
        if( Data != null )
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer() { MaxJsonLength = MaxJsonLength, RecursionLimit = RecursionLimit };
            response.Write( serializer.Serialize( Data ) );
        }
    }
}

So here is how we return it now on your SelectSomethingAjax

public LargeJsonResult SelectSomthingAjax()
{
    var model = GetRecords();

    return new LargeJsonResult
    {
        MaxJsonLength = int.MaxValue,
        JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet,
        Data = new GridModel<YourViewModel>
        {
            Data = model.YourViewModel
        }
    };
}

If you notice we omitted the [GridAction] attribute as it returns the ActionResult as a JsonResult and since we are already returning it we don’t need that attribute.   Now with that solution I can output more records without that error.


13 thoughts on “Large JSON Result for Telerik’s MVC Grid

  1. MC Ren

    Thanks for posting this. You saved me a great deal of time sleuthing interwebs.

    Reply
  2. David

    Thanks for the great help Raymund.

    The only issue is that we are using [GridAction(EnableCustomBinding = true)] attribute. Removing the attribute means that we loose the paging functions.

    Guess it’s back to the drawing board.

    Reply
  3. Pingback: JavaScriptSerializer seems to ignore the maxJsonLength configuration | PHP Developer Resource

  4. Pingback: Large JSON Result for Telerik’s MVC Grid « tHere's }{asiB

  5. Oz

    Your hearts in the right place, but this messes-up the grid sorting, grouping and filtering because the data that is returned isn’t exactly in the format that the Telerik client side expects it. That’s what the [GridAction] filter attribute does…

    Reply
  6. Pingback: How to resolve JSON serialization error in Telerik MVC grid to populate large dataset | jenyamatya

Leave a Reply