0

I want to send a class array with ajax but, when I make an ajax request, the request does not reach the backend side. When I sent a string array request. It works great. But If the Array contains a class, it is as if no request is made.

This is my javascript class:

var image_base64_code = [];

class images_base64 {
        constructor(id, base64, name) {
            this.id = id;
            this.base64 = base64;
            this.name = name;
        }
    }
//***************************************
//  there are some codes here. For information.
//***************************************

image_base64_code.push(new images_base64(preview_intex, image_base64,name));

This is my ajax request:

$('#Ajax').click(function () {

            var ImageJsonText = JSON.stringify({ image_base64_code: image_base64_code});

            $.ajax({
                url: 'main.aspx/ImageSave',
                dataType: 'json',
                type: 'POST',
                data: ImageJsonText,
                traditional: true,
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert(data.d);
                }
            });
        });
    });

And my backend function:

[WebMethod]
public static bool ImageSave(RequestImage[] image_base64_code)
{


     return 1;
 }

public class RequestImage{
   public string id;
   public string base64;
   public string name;
}
wazz
  • 4,953
  • 5
  • 20
  • 34
Enes Şahin
  • 13
  • 1
  • 5

1 Answers1

0

Use an object

var image_base64_code = {};              // object.
image_base64_code["images"] = [];
image_base64_code["images"].push( ... ); // add new here. 

var ImageJsonText = JSON.stringify(image_base64_code);

JSON.stringify turns objects into strings, so change public static bool ImageSave(RequestImage[] image_base64_code) to accept a string.

public static bool ImageSave(string image_base64_code)
{
    return 1;
}

Inside this method you can convert the string to RequestImage objects (deserialize) with built-in javascript deserializer or a library like JSON.NET (Newtonsoft).


Also see: JSON.stringify doesn't work with normal Javascript array

wazz
  • 4,953
  • 5
  • 20
  • 34