我在通过 AJAX 调用从 Controller 获取对象时遇到了一些问题。准确地说,我想获取包含 IEnumerable 类型属性的对象。
第 1 类:
public class ChartItem
{
public string cName { get; set; }
public string label { get; set; }
public decimal value { get; set; }
public decimal value2 { get; set; }
public string value2Cur { get; set; }
public string value2Unit { get; set; }
public string color { get; set; }
public string strokeColor { get; set; }
public string chartTitle { get; set; }
}
第 2 类:
public class ReportParameter
{
public string ReportName { get; set; }
public string DateFrom { get; set; }
public string DateTo { get; set; }
public string CountryId { get; set; }
public string RegionId { get; set; }
public string RepresentativeId { get; set; }
public string CustomerId { get; set; }
public ExportFormatType ReportFormat { get; set; }
public EReport.ChartType ChartType { get; set; }
public bool EmailFlag { get; set; }
public IEnumerable<ChartItem> chartItems { get; set; }
}
这是执行调用的 Controller :
[HttpPost]
public JsonResult ReloadReportSummary(EReport.ReportParameter rptParam)
{
EMAP.WEB_Bootstrap.Helper.ViewHelper viewHelper = new ViewHelper();
IEnumerable<EReport.ChartItem> resultChart=null;
try
{
EReport.ReportParameter eRpt = new EReport.ReportParameter();
eRpt.ReportName = ((EReport.ReportName)Enum.Parse(typeof(EReport.ReportName), rptParam.ReportName)).ToString();
switch ((EReport.ReportName)Enum.Parse(typeof(EReport.ReportName), rptParam.ReportName))
{
case EReport.ReportName.CRPotentialCustomerList:
//reload the chart data
resultChart =
from cp in db.CustomerProducts
join pr in db.Products on cp.ProductID equals pr.ProductID
group cp by cp.Product.ProductDescription into grp
select new EReport.ChartItem { label = grp.Key, value = grp.Count()};
break;
case EReport.ReportName.CRCustomerProductAppMasterPivot:
//reload the chart data
resultChart =
from cp in db.CustomerProducts
join pr in db.Products on cp.ProductID equals pr.ProductID
group cp by cp.Product.ProductDescription into grp
select new EReport.ChartItem { label = grp.Key, value = grp.Count() };
break;
default:
break;
}
eRpt.chartItems = resultChart;
---EDITED----
var result = eRpt;
return Json(new { Result = "OK", Record = result },
JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Result = "ERROR"});
}
}
这是 AJAX 调用:
$.ajax({
url: urlReportSummary,
data: JSON.stringify(rptParam),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
var len = result.Record.chartItem.length;
},
error: function (ex) {
alert(ex);
}
});
实际上我想遍历每个 Record.chartItem 的对象并在那里做一些处理。但不知何故,返回的记录没有被识别。以下是错误:
"TypeError: result.Record.chartItem is undefined".
我可以知道使用 AJAX 获取数据列表的正确方法是什么吗?
非常感谢
最佳答案
如下更改成功函数并尝试
success: function (result) {
var len = result.Record.chartItems.length;
},
您拼错了属性 chartItems
。我想现在它会起作用
关于javascript - 使用 AJAX 使用 IEnumerable 返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24006692/