无法使用AJAX将数组绑定到列表

时间:2014-06-17 14:55:53

标签: c# javascript jquery ajax json

我正在使用AJAX调用来尝试将数组中的数组绑定到C#中的列表。第二个集合始终为空。


如果您不熟悉DataTable,只需担心dataTableOptions的AJAX部分,因为它与jQuery相同。以下是我到目前为止的情况:

JavaScript

var dataRows = [{ RowCells: ["Test", "Test"] }];
var reportSectionContents = { DataRows: dataRows };
dataTableOptions = {
    processing: true,
    serverSide: true,
    ajax:  {
        url: "/Data/ProcessDataTable",
        type: "POST",
        data: reportSectionContents
    }
};

Action

[HttpPost]
public JsonResult ProcessDataTable(ReportSectionContents reportSectionContents)    

ReportSectionContents

public class ReportSectionContents
{
    public string Title { get; set; }
    public ICollection<string> ColumnHeaders { get; set; }
    public ICollection<ReportRow> DataRows { get; set; }
    public ReportRow TotalRow { get; set; }

    public ReportSectionGraphContents Graph { get; set; }

    public ICollection<ReportSectionContents> LoopContents { get; set; }
}

ReportRow

public class ReportRow
{
    public IList<string> RowCells { get; set; }
}

运行此操作时,将填充操作中的reportSecionContents对象,并且DataRows属性在集合中有1个项目,这是预期的。该项目的实例为ReportRow,但在该对象中,RowCells属性始终为null。

我预计会填充2个字符串项("Test""Test")。我错过了什么?

修改

使用arserbin3的答案,我能够得到更多,但现在我收到一个错误,我的AJAX请求是“无效的JSON原语:后跟JSON字符串”。我使用标准的jQuery AJAX测试了它,它工作正常,所以我很确定这是一个DataTables问题现在(www.datatables.net)。我传递的字符串似乎不正确,但数据表试图解析的信息似乎不喜欢以JSON格式

2 个答案:

答案 0 :(得分:1)

您应该只对设置为&#39;数据&#39;的父对象进行字符串化。 AJAX请求的属性值。 此外,您应将contentType设置为JSON,以便将请求正确地设为application/json

将您的JavaScript代码更改为:

var dataRows = [{ "RowCells": ["Test", "Test"] }];
var reportSectionContents = { DataRows: dataRows };
dataTableOptions = {
    processing: true,
    serverSide: true,
    ajax:  {
        url: "/Data/ProcessDataTable",
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify(reportSectionContents)
    }
};

答案 1 :(得分:-1)

您需要使用JSON.stringify()包围字符串数组。这将使它正确地将字符串数组转换为字符串数组。它以“Test,Test”的形式值而不是正确的数组进入服务器。

var dataRows = [{ RowCells: JSON.stringify(["Test", "Test"]) }];