I'm getting this error:

Internal Server Error: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

I have googled answers for this and have found 2 answers, neither of which seem to be working for me. I have tried to add the maxJsonLength setting to the web.config but it's being ignored. As well, I have tried in the C# code to set MaxJsonLength = int.MaxValue; but I am using MVC 2.0 and it appears this only works in MVC 4? Can anyone help me set the maxJsonLength property properly? Here is where I'm getting the error.

 public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var result = filterContext.Result as ViewResult;
        if (result == null)
        {
            return;
        }

        var jsonResult = new JsonResult
                             {
                              Data = result.ViewData.Model, 
                              JsonRequestBehavior = JsonRequestBehavior.AllowGet
                             };


        filterContext.Result = jsonResult;
    }

2 Answers 11

up vote 1 down vote accepted

I am not sure it works or not but i found some solution , please try below

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

or

public ActionResult SomeControllerAction()
{
  var jsonResult = Json(veryLargeCollection, JsonRequestBehavior.AllowGet);
  jsonResult.MaxJsonLength = int.MaxValue;
  return jsonResult;
}
upvote
  flag
I tried both of these options. The Web.config option is ignored, and unless I'm doing something wrong, it appears MVC2 doesn't have the MaxJsonLength property available. – Mark Highfield

Got it, using the following code

 public ActionResult MyFancyMethod()
 {
     var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
     var result = new ContentResult
     {
         Content = serializer.Serialize(myBigData),
         ContentType = "application/json"
     };
     return result;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.