In this article I will explain how to solve the exception (error) occurring during AJAX calls in ASP.Net MVC i.e. Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
The above exception (error) occurs in ASP.Net MVC when AJAX calls are made using AJAX clients like jQuery AJAX, AngularJS or ReactJS and the length of the AJAX Response exceeds the default predefined limit of 2097152 characters i.e. 4 MB.
Problem
The following exception (error) occurs in ASP.Net MVC when AJAX calls are made to Controller’s Action methods or Web API Action methods using jQuery AJAX or AngularJS.
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Cause
This exception (error) occurs in ASP.Net MVC when AJAX calls are made to Controller’s Action methods or Web API Action methods using jQuery AJAX, AngularJS or ReactJS and the length of the AJAX Response exceeds the default predefined limit of 2097152 characters i.e. 4 MB as per MSDN.
Solutions
Following are the two solutions and both will work individually depending on the MVC version of the project.
Solution #1
The solution to this problem is to set a higher value of maxJsonLength property through Web.Config configuration using the system.web.extensions section as shown below.
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="819200000" />
</webServices>
</scripting>
</system.web.extensions>
Solution #2
If the above solution does not work, then you need to set the JSON length to maximum value inside the Action method of the Controller handling the AJAX call.
[HttpPost]
public JsonResult GetPerson(int personId)
{
Person person = GetPerson(personId);
JsonResult jsonResult = Json(person);
//Set the MaxJsonLength to the maximum value.
jsonResult.MaxJsonLength = int.MaxValue;
//Return the JSON result.
return jsonResult;
}