An issue occurred while serializing or deserializing, specifically with the JavaScriptSerializer and

I am facing an issue while trying to retrieve images from my database. The process works smoothly with small images, but when attempting to do the same with the default Windows 7 images (Desert, Koala, Penguins, Tulips, etc.), I encounter an error:

"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property."

To address this problem, I made changes to my web.config file as follows:

<scripting>
  <webServices>
    <jsonSerialization maxJsonLength="2147483647"/>
  </webServices>
</scripting>

The code snippet used to fetch the images is as follows:

public static byte[] Serialize(object obj)
{
    var binaryFormatter = new BinaryFormatter();
    var ms = new MemoryStream();
    binaryFormatter.Serialize(ms, obj);
    return ms.ToArray();
}


[WebMethod]
public string ObtenerImagen(int id)
{
    DataTable dt = new DataTable();        
    dt = conn.consultarImagen("alertas", id);
    Imagenes img;
    List<Imagenes> lista = new List<Imagenes>();

    for (int i = 0; i < dt.Rows.Count; i++)
    {
        img = new Imagenes();
        img.Id = Convert.ToInt32(dt.Rows[i]["Id"]);
        img.FileName = dt.Rows[i]["FileName"].ToString();
        img.Type = dt.Rows[i]["ContentType"].ToString();
        img.Content = Convert.ToBase64String(Serialize(dt.Rows[i]["Content"]));
        img.IdAlerta = Convert.ToInt32(dt.Rows[i]["IdAlerta"]);
        img.Pie = dt.Rows[i]["PieFoto"].ToString();
        //Populating the list
        lista.Add(img);
        img = null;
    }
    JavaScriptSerializer js = new JavaScriptSerializer();
    string lineas = js.Serialize(lista);
    return lineas;
}

Subsequently, a javascript function is utilized along with Ajax:

 success: function (data) {
        var aRC = JSON.parse(data.d);
        var lineas = "";

        for (var i = 0; i < aRC.length; i++) {
            var id = aRC[i].Id;
            var num = id;
            var rev = aRC[i].FileName;
            var pur = aRC[i].Type;
            var status = aRC[i].Content;
            var imagen = status.substring(36, status.length - 37);
            var owner = aRC[i].IdAlerta;
            var pie = aRC[i].Pie;

            lineas += '<div class="col-lg-3 col-md-4 col-xs-3 thumb marco">';
            lineas += '<a class="thumbnail" href="#">';
            lineas += '<img class="responsive" src="data:image/jpeg;base64,' + imagen + '" />';                    
            lineas += '<p class="text-justify" id="Pie' + i + '">' + pie + '</p>';
            lineas += '</a>';
            lineas += '<span class="btn btn-xs btn-success fa fa-pencil hidden-print" id="EditPie' + i + '"></span>';
            lineas += '<input type="text" class="form-control hidden hidden-print" id="PiePag' + i + '"> <span class="btn btn-xs btn-success fa fa-check hidden hidden-print" id="OkPie' + i + '"></span>';
            lineas += '</div>';
      }
      $('#Imagenes').html(lineas);

I am seeking guidance on how to resolve this issue. Any suggestions would be appreciated.

EDIT: The process works fine with a single image, but encounters an issue when attempting to display multiple images.

Answer №1

One possible solution could be adjusting the maximum JSON length using the instance you have initialized like so:

js.SetMaxJsonLength = Int32.MaxValue;

Have you considered the size of the objects you are trying to include in the JSON? JSON may not handle large objects efficiently, and it might be more effective to load them lazily through AJAX. When dealing with extensive galleries, they often display a loading icon while retrieving specific objects in the background for subsequent items.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that background elements do not become the focus when using MUI backdrop

Currently, we are implementing screen dimming when a custom dialog is open using MUI backdrop. However, even though the screen is "grayed-out," users can still access the items with the keyboard. In the image below, you can see how I move from "show backd ...

The simultaneous use of trackball controls and GUI is not compatible

When I click on them, the GUI changes together and I have looked at other answers. However, I am not sure where to put the listener. I tried putting the listener in render(), but it still doesn't work. How can I fix my code? This coding is related to ...

What is the process for linking an HTML document to another HTML document within a div using jQuery?

Check out my HTML code: <!DOCTYPE html> <html> <head> <title>Hilarious Jokes!</title> <meta charset="utf-8"> <link href="final%20project.css" rel="stylesheet"> <script src=" ...

Encoding MySQL query in JSON

I am working on a script that executes a MySQL query, and if there are rows returned, it encodes a message. However, I would like the message to include not only its own content but also the entire result of the query. Here is the code snippet I am current ...

What steps should I take to customize the design of my Stripe subscription payment page?

I am having trouble with the alignment of the subscription payment page, which is currently displaying all information in a single line. I would like to format it like a traditional payment form with card number, CVV, and expiry on separate lines rather th ...

Verifying Text Presence within a <div> Element Using C# Selenium

Is there a way to verify the presence of specific text on a webpage? I have attempted various solutions, but none have been successful so far. <div style="display:inline-block;vertical-align:top"> text I am trying to locate<br> more te ...

Utilizing an EJS variable within a React render function with webpack - A Guide

I am looking for a way to display personalized information stored in a MySQL database to my users. I am using ejs, webpack, and React for my project. While I found some guidance on how to achieve this without webpack, it doesn't quite fit my needs. Th ...

Every time I click a button, I am trying to add JSON objects into an array and then show the outcomes

Currently, my goal is to create a random selection feature from an array that users can contribute to by clicking a button. I am a bit unsure about how to proceed with this task. The application is developed in React and it utilizes the movieDB's API ...

Reacting to a click event to display a new image

I'm looking to create a webpage with multiple images where clicking on one image will open another image with its description. The images are stored locally in my library. I tried using the href attribute in the html tag, but it doesn't accept lo ...

Issue when activating Materialize Bootstrap

I'm facing an issue with my code. I have implemented a feature where a modal should be triggered after a user successfully adds a new user. However, I am using Materialize and the modal is not being triggered. Below is a snippet of my code: <div i ...

Flowplayer playlist stops after playing the first clip

I am having issues with my flowplayer configuration, as it is not behaving as I expected. After the first video ends, I want the second and subsequent videos to play automatically. Can anyone provide some guidance on how to achieve this? $f("player", "/fl ...

At times, JavaScript interacts with Selenium to click on the login button before I have the chance

I have a challenge while attempting to log in to Twitter using Selenium webdriver, here is the code I am working with: const {Builder, By} = require("selenium-webdriver"); (async function example() { let driver = await new Builder().forBrowser(' ...

Is the element loaded but not appearing on screen?

I am facing an issue when using ajax to send data to a PHP server and displaying it in the view. Even though the data loads successfully (checked in console), it does not display in the view. Can someone please help me resolve this? Here is my code : Vie ...

Choosing CSS/JS selector: Pick the final element with a class that does not match

My goal is to extract the most recent td element from the latest tr within an HTML table, ensuring that the latest td does not belong to the disabled class. I am attempting to achieve this using pure JavaScript with CSS selectors (without relying on jQuer ...

Using React: Passing the state value of Child1 to the Parent component, then passing it back down to Child2 from

Within my application, I've implemented two child components: 'FoodScreen' and 'OperationScreen', along with a parent component called 'Desk'. I am passing a JSON array variable to the FoodScreen component in order to sel ...

Local variable reference getting lost in a loop during a jQuery Ajax call

Currently, I am facing an issue with my jQuery ajax calls within a loop. The problem arises when each ajax call returns and I need to retrieve a specific value associated with the original call. However, due to further iterations in the loop, the value of ...

What are some methods to eliminate recursion within an object or array?

I am facing an issue with a specific array structure. $data = new stdClass(); $data->foo = [ 'foo1' => &$data, 'foo2' => 23, ]; $data->bar = new stdClass(); $data->nar->object = [ 'bar1' = ...

Unusual navigation patterns in Angular

https://i.sstatic.net/kdh4A.png My Mean app is set up with the Angular app residing in the '/dashboard' path. The home page of the app works fine. Reloading the app returns the page it was on. Even routes with '/dashboard/anything/anything& ...

The property linerGradiant of r cannot be destructured because it is not defined

I encountered the error "Cannot destructure property linerGradiant of r as it is undefined" during runtime, making it difficult to debug. The issue seems to stem from the compiled JS file, which is hard to read. The function is defined as follows: functio ...

Save information to a server-side .xml file with the use of either JavaScript or PHP

I have a website built using HTML and JavaScript. Currently, I am successfully retrieving data from a server-side .xml file on the site. Everything is working perfectly! However, I am facing issues with allowing users to input data into a field and save ...