I have a WebMethod with the following signature:
[WebMethod]
public void SaveRoute(int id, Coordinates[] coordinates)
{
}
Where Coordinates is:
/// <summary>
/// A position on the globe
/// </summary>
public class Coordinates
{
public decimal Longitude { get; protected set; }
public decimal Latitude { get; protected set; }
public Coordinates(decimal latitude, decimal longitude)
{
this.Longitude = longitude;
this.Latitude = latitude;
}
}
I want to call this from a jQuery ajax method like this one:
$.ajax({
type: "POST",
url: "Routes.asmx/SaveRoute",
cache: false,
contentType: "application/json; charset=utf-8",
data: '{"id":1, ,"coordinates": "Longitude":123,"Latitude":456}',
dataType: "json",
success: handleHtml,
error: ajaxFailed
});
What would I have to supply in the data property for a correct deserialisation?
I have now solved it:
Thanks for all the help, I eventually managed to get what I wanted with the following code:
var coords = new Array();
for (ckey in flightPlanCoordinates) {
var thisWaypoint = { "Longitude": flightPlanCoordinates[ckey].lng(), "Latitude": flightPlanCoordinates[ckey].lat() };
coords.push(thisWaypoint);
}
var data = { "id": 1, "coordinates": coords };
if (flightPlanCoordinates) {
$.ajax({
type: "POST",
url: "Routes.asmx/SaveRoute",
cache: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
dataType: "json",
success: handleHtml,
error: ajaxFailed
});
}
I reverse engineered the JSON by sending some down with another method:
[WebMethod]
public Coordinates[] Get()
{
return new Coordinates[]
{
new Coordinates(123, 456),
new Coordinates(789, 741)
};
}
It is also important that you have a public parameterless constructor in your class and your property's setters are public:
/// <summary>
/// A position on the globe
/// </summary>
public class Coordinates
{
public decimal Longitude { get; set; }
public decimal Latitude { get; set; }
public Coordinates()
{
}
public Coordinates(decimal latitude, decimal longitude)
{
this.Longitude = longitude;
this.Latitude = latitude;
}
}