true

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.

2 upvote
  flag
Your solutions works on MVC 3. – MatteoSp
1 upvote
  flag
@Matteo Are you sure? This is an old question and I can't remember but apparently I tagged it as MVC3. Unfortunately I can't see the version/date when it got fixed/closed: aspnet.codeplex.com/workitem/3436 – Martin Buberl
1 upvote
  flag
Sure, I'm working with MVC 3 and it works. And fortunately, because in MVC 3 you don't have the "MaxJsonLength" properties cited in the accepted answer. – MatteoSp

8 Answers 11

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.

You could also use ContentResult as suggested here instead of subclassing JsonResult.

var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };

return new ContentResult()
{
    Content = serializer.Serialize(data),
    ContentType = "application/json",
};
1 upvote
  flag
in my case, working on a throwaway app, this solution worked best for me. saved implementing jsonresult. thanks! – Christo
up vote 172 down vote accepted

It appears this has been fixed in MVC4.

You can do this, which worked well for me:

public ActionResult SomeControllerAction()
{
  var jsonResult = Json(veryLargeCollection, JsonRequestBehavior.AllowGet);
  jsonResult.MaxJsonLength = int.MaxValue;
  return jsonResult;
}
1 upvote
  flag
Great answer! thank you! – GG.
upvote
  flag
I am setting a json string into a ViewBag.MyJsonString property but getting same error in my view at runtime on following javascript line: var myJsonObj = @Html.Raw(Json.Encode(ViewBag.MyJsonString)); – Faisal Mushtaq
1 upvote
  flag
Hey @orionedvards ,@GG, @ MartinBuberl I am facing the same maxJson issue but when posting data to the controller , How can I handle this , I spent so much time searching about this .Any help would be grateful. – katmanco
upvote
  flag
great answer thanks – Younis Qadir
upvote
  flag
Thanks Orion, it worked fine. – User5590

No need for a custom class. This is all that is needed:

return new JsonResult { Data = Result, MaxJsonLength = Int32.MaxValue };

where Result is that data you wish to serialize.

upvote
  flag
Error 137 'System.Web.Mvc.JsonResult' does not contain a definition for 'MaxJsonLength' – PUG
upvote
  flag
Where are you getting this error? – John
upvote
  flag
c#.net mvc3...... – PUG
upvote
  flag
I know it works on MVC4. I will check MVC3. – John
upvote
  flag
does not work on MVC3 – Dave Lawrence
upvote
  flag
This worked for me, however still needed to add : JsonRequestBehavior = JsonRequestBehavior.AllowGet – DubMan

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:

var listItems = (from u in Users where u.name.Contains(term) select u).ToList();

The problem here is "select u" that get all fields. So, if you have big pictures, booomm.

How to solve? very, very simple.

var listItems = (from u in Users where u.name.Contains(term) select new {u.Id, u.Name}).ToList();

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.

upvote
  flag
I wouldn't assume that the user in this case wants to filter their data. Some people have requirements to bring back a large amount of rows from the database... – Simon Nicholls

If use Json.NET to generate the json string, it doesn't need to set MaxJsonLength value.

return new ContentResult()
{
    Content = Newtonsoft.Json.JsonConvert.SerializeObject(data),
    ContentType = "application/json",
};

I solved the issue by following this link

namespace System.Web.Mvc
{
public sealed class JsonDotNetValueProviderFactory : ValueProviderFactory
{
    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        if (controllerContext == null)
            throw new ArgumentNullException("controllerContext");

        if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            return null;

        var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
        var bodyText = reader.ReadToEnd();

        return String.IsNullOrEmpty(bodyText) ? null : new DictionaryValueProvider<object>(JsonConvert.DeserializeObject<ExpandoObject>(bodyText, new ExpandoObjectConverter()), CultureInfo.CurrentCulture);
    }
}

}

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        //Remove and JsonValueProviderFactory and add JsonDotNetValueProviderFactory
        ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
        ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory());
    }

You need to read from the configuration section manually before your code returns a JsonResult object. Simply read from web.config in single line:

        var jsonResult = Json(resultsForAjaxUI);
        jsonResult.MaxJsonLength = (ConfigurationManager.GetSection("system.web.extensions/scripting/webServices/jsonSerialization") as System.Web.Configuration.ScriptingJsonSerializationSection).MaxJsonLength;
        return jsonResult;

Be sure you defined configuration element in web.config

Not the answer you're looking for? Browse other questions tagged or ask your own question.