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
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.
The default value for maxJsonLength is 102400.
If you are still getting error, even after settings maxjsonlength in web.config, then you can directly use C# Code in Controller as below
var serializer = new JavaScriptSerializer();
// For simplicity just use Int32's max value.
// You could always read the value from the config section mentioned above.
serializer.MaxJsonLength = Int32.MaxValue;
var resultData = new { Value = "Testing", Text = "Hello World" };
var result = new ContentResult{
Content = serializer.Serialize(resultData),
ContentType = "application/json"
};
return result;
That's it.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly