Changing the default maxJsonLength in web config won't work when trying to return a JsonResult, because asp.net will try to serialize your object internally while completely ignoring the maxJsonLenght you set.
One simple way to fix this, is to return a string instead of a JsonResult in your method, and instance a new JavaScriptSerializer with your custom maxJsonLenght, something like this:
[HttpPost]
public string MyAjaxMethod()
{
var veryBigJson = new object();
JavaScriptSerializer s = new JavaScriptSerializer
{
MaxJsonLength = int.MaxValue
};
return s.Serialize(veryBigJson);
}
And then in your view you just parse it back into a json with JSON.parse(data)
Another way would be creating your own JsonResult class when you can actually control the maxJsonLenght, something like this:
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(object data,JsonRequestBehavior jsonRequestBehavior=JsonRequestBehavior.DenyGet,int maxJsonLength=Int32.MaxValue)
{
Data = data;
JsonRequestBehavior = jsonRequestBehavior;
MaxJsonLength = maxJsonLength;
RecursionLimit = 100;
}
public new int MaxJsonLength { get; set; }
public new int RecursionLimit { get; set; }
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));
}
}
}
And on your method you just change the type and return a new instance of the class
[HttpPost]
public LargeJsonResult MyAjaxMethod()
{
var veryBigJson = new object();
return new LargeJsonResult(veryBigJson);
}
Source: https://brianreiter.org/2011/01/03/custom-jsonresult-class-for-asp-net-mvc-to-avoid-maxjsonlength-exceeded-exception/