king yau king yau - 29 days ago 6
Ajax Question

How do i structure a string array in ajax and pass it to asp?

In my project, I want to use ajax for the communication between JS and ASP. However, I got 500 error in it.

JSON string in JS ajax:

{lists: [{'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a111', 'colour': 'red'}, {'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a222', 'colour': 'green'}]}


C#:

[WebMethod]
public static string GetCurrentTime(List<string> lists)
{
return "text string" ;
}


FULL AJAX:

var dataJson = "{lists: [{'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a111', 'colour': 'red'}, {'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a222', 'colour': 'green'}]}";
$.ajax({
type: "POST",
url: URL,
data: dataJson ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
console.log(response.d);
}

Answer

Try using JSON.stringify as below with a object instead of List<string>,

var dataJson = {lists: [{'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a111', 'colour': 'red'}, {'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a222', 'colour': 'green'}]};
     $.ajax({
            type: "POST",
            url: URL,
            data: JSON.stringify(dataJson),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
function OnSuccess(response) {
        console.log(response.d);
    }

C#

public class Data { 
        public string ID {get;set;}
         public string colour {get;set;}   // This can be renamed into Pascal case here and in the json
       }

[WebMethod]
 public static string GetCurrentTime(List<Data> lists)
 {
     return "text string" ;
 }
Comments