我正在嘗試將資料從JsonResult我的ASP.Net Core (3.1) Razor 頁面應用程式中的方法回傳到 Razor 頁面,但是,我遇到了問題。
當我除錯時,我可以看到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)
}
})

uj5u.com熱心網友回復:
修復類,洗掉所有屬性并添加 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));
},
.....
uj5u.com熱心網友回復:
您可以將回傳的物件視為服務器端類的實體:
success: function (dataPoint) {
alert(`X: ${dataPoint.x}\nY: ${dataPoint.y}`);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/360884.html
標籤:json asp.net核心 剃刀页面 画布js 结果
