javascriptasp.net-mvcasp.net-ajax

"Error serializing or deserializing using JavaScriptSerializer JSON. The length of the string exceeds the value set in the maxJsonLength property."


I need to send a JSON from JavaScript to a controller. The length of the JSON is 2199215.

I know that the maximum length of a JSON is 2097152, but I also know that this can be changed from the web.config. I tried changing it, but it still gives me the same error. For now I have split the request into more than one, so as not to exceed the maximum length, but I would prefer to do everything in a single request. Do you know why the MaxJsonLength I set in the web.config is not considered? Do you have any idea how to solve it?

This is the Ajax request I made

$.ajax({
        url: getUrl("Canali/RicalcolaRenderCanaliRows"),
        method: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({
            canali: canaliInfo
        }),
        dataType: "html",
        success: function (html) {
            // append the rendered rows to the channels' table
            $("#elencoCanali").find("tbody").append(html);
            // update info about the channels (e.g. the number of loaded channels)
            ricalcola_reloadInfo();
        },
        error: function (xhr, error) {
            showErrorMessage("Impossibile caricare i canali selezionati. Riprovare")
        },
        complete: function () {
            // riabilita i controlli sia in caso di successo che di errore
            ricalcola_enableControls();
        }
    });

And this is the Controller:

public PartialViewResult RicalcolaRenderCanaliRows(IEnumerable<CanaleDetailed> canali)
    {
        return PartialView(canali);
    }

Solution

  • You need to change the length when you return the json in the controller

    var jsonResult = Json(myobject, JsonRequestBehavior.AllowGet);
    jsonResult.MaxJsonLength = int.MaxValue;
    return jsonResult;