我有一个具有以下签名的 WebMethod:
[WebMethod]
public void SaveRoute(int id, Coordinates[] coordinates)
{
}
坐标在哪里:
/// <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;
}
}
我想从 jQuery ajax 方法调用它,如下所示:
$.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
});
我必须在数据属性中提供什么才能正确反序列化?
我现在已经解决了:
感谢大家的帮助,我最终通过以下代码得到了我想要的东西:
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
});
}
我通过使用另一种方法发送一些内容来对 JSON 进行逆向工程:
[WebMethod]
public Coordinates[] Get()
{
return new Coordinates[]
{
new Coordinates(123, 456),
new Coordinates(789, 741)
};
}
同样重要的是,你的类中有一个公共(public)的无参数构造函数,并且你的属性的 setter 是公共(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;
}
}
最佳答案
我建议使用 JSON.stringify 构建“JSON”字符串。 使用 JSON.stringify,您可以将坐标数组转换为 JSON 字符串表示形式。 示例:
var id = 2;
var coords = new Array();
coords[0] = { Longitude: 40.0, Latitude: 76.0 };
coords[1] = { Longitude: 42.0, Latitude: 77.0 };
$.ajax({
type: "POST",
url: "Routes.asmx/SaveRoute",
cache: false,
contentType: "application/json; charset=utf-8",
data: '{ "id":' + JSON.stringify(id) + ', "coordinates":' + JSON.stringify(coords) + '}',
dataType: "json",
success: handleHtml,
error: ajaxFailed });
如果您将 SaveRoute Web 方法放置在 aspx 网站上,则可以使用 ScriptManager 生成 页面方法和脚本类型(请参阅MSDN有关GenerateScriptTypeAttribute的文档)。
关于jquery - 从 jQuery ajax 使用类数组调用 asmx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7112922/