我正在尝试将数据从我的ASP.Net Core (3.1) Razor应用程序中的一个ASP.Net方法返回到Razor,但是,我遇到了问题。
调试时,我可以看到Page中的OnGetCarList
方法正在被击中,但是当数据被返回到Ajax Success
函数并使用alert
输出时,代码中没有错误,这就是我所看到的:
Ajax调用( Razor中)
$.ajax({
method: 'get',
url: '/SPC/Index?handler=CarList',
contentType: "application/json",
dataType: "json",
success: function (data) {
alert(data);
//addData(data)
}
})
页面模型
public JsonResult OnGetCarList()
{
var converted = DateTime.Now.ToOADate();
DateTime one = DateTime.Now;
DateTime two = DateTime.Now.AddDays(1);
DateTime three = DateTime.Now.AddDays(2);
DateTime sTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var c_one = (long)(one - sTime).TotalMilliseconds;
var c_two = (long)(two - sTime).TotalMilliseconds;
var c_three = (long)(three - sTime).TotalMilliseconds;
dataPoints = new List<DataPoint>();
dataPoints.Add(new DataPoint(c_one, 100));
dataPoints.Add(new DataPoint(c_two, 200));
dataPoints.Add(new DataPoint(c_three, 300));
return new JsonResult(dataPoints);
}
//DataContract for Serializing Data - required to serve in JSON format
[DataContract]
public class DataPoint
{
public DataPoint(double x, double y)
{
this.x = x;
this.Y = y;
}
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "x")]
public Nullable<double> x = null;
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "y")]
public Nullable<double> Y = null;
}
如有任何指导,将不胜感激。
谢谢。
更新
我将Ajax调用更新到Serge所说的内容,现在Alert
给出了这样的内容。
$.ajax({
method: 'get',
url: '/SPC/Index?handler=CarList',
contentType: "application/json",
dataType: "json",
success: function (data) {
alert(JSON.stringify(data));
//addData(data)
}
})
发布于 2021-11-19 16:39:56
修复类,删除所有属性并添加getter/setter
public class DataPoint
{
public DataPoint(double x, double y)
{
X = x;
Y = y;
}
public double? X {get; set;}
public double? Y {get; set;}
}
使用JSON.stringify进行测试
$.ajax({
....
success: function (data) {
alert(JSON.stringify( data));
},
.....
发布于 2021-11-20 07:42:42
可以将返回的对象视为服务器端类的实例:
success: function (dataPoint) {
alert(`X: ${dataPoint.x}\nY: ${dataPoint.y}`);
}
https://stackoverflow.com/questions/70037382
复制相似问题