MaxJsonLength error during serialization or deserialization using the JSON JavaScriptSerializer in ASP.NET MVC


When I am trying to return JSON data to my jQuery Datatable(Ajax based), It is working in some cases, but it is throwing below error in some cases

Exception information: 
Exception type: InvalidOperationException 
Exception message: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

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

Here is my current code

         public JsonResult ShowDataTable(bool? clear,string types, string status)
        {

            NameValueCollection nvc = HttpUtility.ParseQueryString(Request.Url.Query);
            string sEcho = nvc["sEcho"].ToString();
            string sSearch = nvc["sSearch"].ToString();
            int iDisplayStart = Convert.ToInt32(nvc["iDisplayStart"]);
            int iDisplayLength = Convert.ToInt32(nvc["iDisplayLength"]);

          // more code here like database call etc.
          // code removed for clearity


    return Json(new { sEcho = sEcho, iTotalRecords = TotlCount, iTotalDisplayRecords = TotlCount, aaData = List3 }, JsonRequestBehavior.AllowGet);
                
            
        }

How do I resolve this issue? Thank you


Asked by:- jon
0
: 79 At:- 9/6/2018 4:34:49 PM
ASP.NET C# JSON






1 Answers
profileImage Answered by:- manish

For ASP.NET MVC, you need to MaxJsonLength to int.Maxvalue in your controller, so return JSON like this

public JsonResult ShowDataTable(bool? clear,string types, string status)
        {

           //Some code here


   var jsonResult = Json(new { sEcho = sEcho, iTotalRecords = TotlCount, iTotalDisplayRecords = TotlCount, aaData = List3 }, JsonRequestBehavior.AllowGet);
                   jsonResult.MaxJsonLength = int.MaxValue;
                   return jsonResult;
                
            
        }

For those who are getting error while working on ASP.NET Web API, go to your web.config and set the MaxJsonLength property

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

The above solutions should reaolve your issue.

1
At:- 9/7/2018 12:04:30 PM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use