In one of my controller actions I am returning a very large JsonResult
to fill a grid.
I am getting the following InvalidOperationException
exception:
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Setting the maxJsonLength
property in the web.config
to a higher value unfortunately does not show any effect.
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644"/>
</webServices>
</scripting>
</system.web.extensions>
I don't want to pass it back as a string as mentioned in this SO answer.
In my research I came across this blog post where writing an own ActionResult
(e.g. LargeJsonResult : JsonResult
) is recommended to bypass this behaviour.
Is this then the only solution?
Is this a bug in ASP.NET MVC?
Am I missing something?
Any help would be most appreciated.
You need to read from the configuration section manually before your code returns a JsonResult object. Simply read from web.config in single line:
Be sure you defined configuration element in web.config
You can try define in your LINQ expression only the field's that you will need.
Example. Imagine that you have an Model with Id, Name, Phone and Picture (byte array) and need to load from json into an select list.
LINQ Query:
The problem here is "select u" that get all fields. So, if you have big pictures, booomm.
How to solve? very, very simple.
The best practices is select only the field that you will use.
Remember. This is a simple tip, but can help many ASP.NET MVC developpers.
this worked for me
It appears this has been fixed in MVC4.
You can do this, which worked well for me:
Unfortunately the web.config setting is ignored by the default JsonResult implementation. So I guess you will need to implement a custom json result to overcome this issue.
Alternative ASP.NET MVC 5 Fix:
In my case the error was occurring during the request. Best approach in my scenario is modifying the actual
JsonValueProviderFactory
which applies the fix to the global project and can be done by editing theglobal.cs
file as such.add a web.config entry:
and then create the two following classes
This is basically an exact copy of the default implementation found in
System.Web.Mvc
but with the addition of a configurable web.config appsetting valueaspnet:MaxJsonLength
.