Problem Statement

Many people had faced with their MVC Applications with the following issue.

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

Why this issue?

The reason for this issue is, trying to return huge JSON data to the view. The fact is, by default JsonResult can return up to 102400 characters i.e.., 100KB for improving bandwidth and performance

Solution

We need to increase this charecter count as follows in your action method while returning JsonResult.

public JsonResult GetData()
        {
            JsonResult result = Json(new
            {
                rows = list.ToArray()
            }, JsonRequestBehavior.AllowGet);

            result.MaxJsonLength = int.MaxValue;

            return result;
        }

as you can see in the above method we assigned MaxJsonLength property with int.MaxValue as this variable is of type int? and cannot assign more than int.MaxValue i.e.., 2147483647 characters.

In some forums and blogs provided a solution by adding the following configuration in web.config

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

But this won’t work as the value of the MaxJsonLength property applies only to the internal JavaScriptSerializer instance that is used by the asynchronous communication layer to invoke Web services methods.

Hope this will help you. Please comment me

Happy Coding 🙂