AJAX Post大量JSON对象返回NULL

时间:2018-02-03 23:19:39

标签: arrays json ajax asp.net-mvc asp.net-ajax

我正在尝试从JSON对象数组生成我的控制器上的excel文件。我只传递了一个JSON对象,并且我使用的相同方法似乎不适用于Lists或JSON数组。

AJAX生成对象:

    $.ajax({
        type: "GET",
        url: '/home/GetInfoToExportCalgary',
        success: function (data) {
            //console.log(data);
            CalgaryBookingInfo = data;

            for (var i = 0; i < CalgaryBookingInfo.length; i++) {
                if (CalgaryBookingInfo[i].length != 0) {
                    //console.log(CalgaryBookingInfo[i][0].Company + " has bookings")

                    var SumTime = 0;
                    for (var j = 0; j < CalgaryBookingInfo[i].length; j++)
                    {
                        CalgaryNotNullBookings.push({
                            Company: CalgaryBookingInfo[i][j].Company,
                            Location: CalgaryBookingInfo[i][j].Location,
                            PaidHours: CalgaryBookingInfo[i][j].HoursPaid,
                            Start: CalgaryBookingInfo[i][j].Start,
                            End: CalgaryBookingInfo[i][j].End,
                            Time: CalgaryBookingInfo[i][j].Time,
                            Total: SumTime + CalgaryBookingInfo[i][j].Time
                        });
                        SumTime += CalgaryBookingInfo[i][j].Time;
                    }

                    CalgaryNotNullBookings.push({
                        Company: "",
                        Location: "",
                        PaidHours: "",
                        Start: "",
                        End: "",
                        Time: "",
                        Total: SumTime
                    });
                }
            }
            console.log(CalgaryNotNullBookings);
            //buildHtmlTable(RetreivedClients);
        }
    })

AJAX发送数组:

这里我只是发送一个POST,其中包含我之前生成的数据,并在单击按钮时调用。

    function ExportCalgary(data) {
        $.ajax({
            type: "POST",
            url: '/home/ExportCalgary',
            data: data,
            success: function (data) {
                console.log("huehuehuehuehueh");
                if (data.status) {
                    //Refresh the calender
                    //location.reload();
                    $('#myModalSave').modal('hide');
                }
            },
            error: function () {
                alert('Failed');
            }
        })
    }

控制器POST功能:

[HttpPost]
public JsonResult ExportCalgary(List<ClientBookingInfo> e)
{
    var status = false;

    //string[] columns = { "Company", "Location", "PaidHours", "Start", "End", "Time" , "Total" };
    //byte[] filecontent = ExcelExportHelper.ExportExcel(dataToConvert, "Technology", true, columns);
    //return File(filecontent, ExcelExportHelper.ExcelContentType, "CalgaryClientInfo_" + DateTime.Now.Year+"_" + DateTime.Now.Month + ".xlsx");

    ExcelPackage excel = new ExcelPackage();
    var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
    workSheet.TabColor = System.Drawing.Color.Black;
    workSheet.DefaultRowHeight = 12;
    //Header of table  
    //  
    workSheet.Row(1).Height = 20;
    workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
    workSheet.Row(1).Style.Font.Bold = true;
    workSheet.Cells[1, 1].Value = "Company";
    workSheet.Cells[1, 2].Value = "Location";
    workSheet.Cells[1, 3].Value = "PaidHours";
    workSheet.Cells[1, 4].Value = "Start";
    workSheet.Cells[1, 5].Value = "End";
    workSheet.Cells[1, 6].Value = "Time";
    workSheet.Cells[1, 7].Value = "Total";
    //Body of table  
    //  
    int recordIndex = 2;
    for(int i = 0; i < e.Count; i++)
    { 
        workSheet.Cells[recordIndex, 1].Value = e[i].Company;
        workSheet.Cells[recordIndex, 2].Value = e[i].Location;
        workSheet.Cells[recordIndex, 3].Value = e[i].PaidHours;
        workSheet.Cells[recordIndex, 4].Value = e[i].Start;
        workSheet.Cells[recordIndex, 5].Value = e[i].End;
        workSheet.Cells[recordIndex, 6].Value = e[i].Time;
        workSheet.Cells[recordIndex, 7].Value = e[i].Total;
        recordIndex++;
    }
    workSheet.Column(1).AutoFit();
    workSheet.Column(2).AutoFit();
    workSheet.Column(3).AutoFit();
    workSheet.Column(4).AutoFit();
    workSheet.Column(5).AutoFit();
    workSheet.Column(6).AutoFit();
    workSheet.Column(7).AutoFit();
    string excelName = "CalgaryClientInfo_" + DateTime.Now.Year+"_" + DateTime.Now.Month;
    using (var memoryStream = new MemoryStream())
    {
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment; filename=" + excelName + ".xlsx");
        excel.SaveAs(memoryStream);
        memoryStream.WriteTo(Response.OutputStream);
        Response.Flush();
        Response.End();

        status = true;
    }



    return new JsonResult { Data = new { status = status } };
}

目前,当我调试时,List “ClientBookingInfo e”返回NULL,我不确定会出现什么问题。它可能是JSON的编码或数据类型吗?我是否遗漏了一些行,这些行指定我发送的JSON将是一个数组?

此处还有类ClientBookingInfo:

public class ClientBookingInfo
{
    public string Company { get; set; }
    public string Location { get; set; }
    public int PaidHours { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
    public int Time { get; set; }
    public double Total { get; set; }
}

提前致谢! :)

1 个答案:

答案 0 :(得分:1)

发布复杂数据时,您应该发送对象的JSON字符串版本,同时将contentType指定为application/json

您可以使用JSON.stringify方法将数组转换为相应的json字符串。

var data = [];
data.push({ Company: "Microsoft", Location: "Redmond" , Total:123 });
data.push({ Company: "UrbanScience", Location:"Detroit", Total:456 });

$.ajax({
    type: "POST",
    url: '@Url.Action("ExportCalgary")',
    data: JSON.stringify(data),
    contentType: "application/json",
    success: function(data) {
        console.log("data :", data);
        // Do something with the response
    },
    error: function() {
        alert('Failed');
    }
});

现在,模型绑定器将能够正确绑定ajax请求中的数据,并且您的操作方法参数中不会出现null

另外,通过ajax下载文件可能不起作用。考虑对您的action方法执行正常(非ajax)表单提交,该方法可以返回文件。此外,如果构建文件所需的数据在服务器代码中可用(让我们说它位于可以读取的db表中),我建议您发送所需的最小数据(如唯一的{{1服务器并让服务器读取数据并使用此Id并使用它来返回文件。

如果你可以将id传递给可以返回文件的action方法,你可以使用Id方法从javascript调用它。

window.open

或将当前网址设置为下载网址

window.open("/Documents/Download?id=2");

假设您有window.location.href = "/Documents/Download?id=2"; 操作方法,该方法采用Download参数并返回文件。