– Getting “The JSON request was too large to be deserialized”

I'm getting this Error:

The JSON request was too large to be deserialized.

Here's a scenario where this occurs. I have a class of country which hold a list of shipping ports of that country

public class Country
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Port> Ports { get; set; }

I use KnockoutJS on the client side to make a cascading drop downs. So we have an array of two drop downs, where the first one is country, and the second one is ports of that country.

Everything is working fine so far, this my client side script:

var k1 = k1 || {};
$(document).ready(function () {

    k1.MarketInfoItem = function (removeable) {
        var self = this;
        self.CountryOfLoadingId = ko.observable();
        self.PortOfLoadingId = ko.observable();
        self.CountryOfDestinationId = ko.observable();
        self.PortOfDestinationId = ko.observable();  

    k1.viewModel = function () {
        var marketInfoItems = ko.observableArray([]),
            countries = ko.observableArray([]),

            saveMarketInfo = function () {
                var jsonData = ko.toJSON(marketInfoItems);
                    url: 'SaveMarketInfos',
                    type: "POST",
                    data: jsonData,
                    datatype: "json",
                    contentType: "application/json charset=utf-8",
                    success: function (data) {
                        if (data) {
                            window.location.href = "Fin";
                        } else {
                            alert("Can not save your market information now!");

                    error: function (data) { alert("Can not save your contacts now!"); }

            loadData = function () {
                $.getJSON('../api/ListService/GetCountriesWithPorts', function (data) {
        return {
            MarketInfoItems: marketInfoItems,
            Countries: countries,
            LoadData: loadData,
            SaveMarketInfo: saveMarketInfo,
    } (); 

The problem occurs when a country like China is selected, which has lots of ports. So if you have 3 or 4 times "China" in your array and I want to send it to the server to save. The error occurs.

What should I do to remedy this?

Best Solution

You have to adjust the maxJsonLength property to a higher value in web.config to resolve the issue.

            <jsonSerialization maxJsonLength="2147483644"/>

Set a higher value for aspnet:MaxJsonDeserializerMembers in the appSettings:

  <add key="aspnet:MaxJsonDeserializerMembers" value="150000" />

If those options are not working you could try creating a custom json value provider factory using JSON.NET as specified in this thread.

Related Question