如何将类型对象的json数组传递给MVC控制器类

时间:2019-01-30 09:07:31

标签: javascript c# arrays json asp.net-mvc

我正在尝试将JSON数组传递到控制器。我希望能够从JSON数组中将数据发布到数据库,该JSON数组已填充并通过客户端中的javascript传递给控制器​​。但是,它在控制器中未收到任何东西。我的控制器收到一个空值作为参数。

以下是我的控制器:

  [HttpPost]
    [SiteAuthorize]
    public ActionResult SaveDashboard(List<Dashboard> dashboards)
    {
        try
        {

            string result = "";
            return Json(new { Result = result, Message = "" }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(new { Result = "Error", Message = ex.Message }, JsonRequestBehavior.AllowGet);
        }
    }

以下是我的javascript:

    var dashboards = {
    "DashboardName": '',
    "Width": '',
    "Height": '',
       "DashboardCell": [
           {
               "DashCellId": '',
               "x": '',
               "y": '',
               "DashWidth": '',
               "DashHeight": '',
               "colspan": '',
               "rowspan": '',
               "Active": '',
               "CellValue": '',
               "cellClass": '',
               "previousElementSibling": ''
           }
        ]
    };

    var tablestructure = $("#TableStructure").val();
    var savename = document.getElementById("namedash").value;

    var table = document.getElementById("table");
    var width = table.clientWidth;
    var height = table.clientHeight;
    var DashboardCell = [];
    dashboards.DashboardName = savename;
    dashboards.Width = width;
    dashboards.Height = height;
    for (var i = 0, row; row = table.rows[i]; i++)
    {

        //iterate through rows
        //rows would be accessed using the "row" variable assigned in the for loop
        for (var j = 0, col; col = row.cells[j]; j++)
        {
            for (var x = 0; x < col.attributes.length; x++)
            {
                if (col.attributes[x].localName == "colspan") {
                    var colspan = col.attributes[x].value;
                }
                else if (col.attributes[x].localName == "rowspan") {
                    var rowspan = col.attributes[x].value;
                }
                else if (col.attributes[x].localName == "class")
                {
                    var cellClass = col.attributes[x].value;
                }
            }

            var res = col.id.split(", ");
            var x = parseInt(res[0]);
            var y = parseInt(res[1]);
            var DashHeight = col.clientHeight;
            var DashWidth = col.clientWidth;
            if (j > 0) {
                var previousElementSibling = col.previousElementSibling.id;
            }
            else {
                var previousElementSibling = '';
            }
            var DashCellID = col.id;
            var CellValue = col.innerText;
            var DashCell = { DashCellId: DashCellID, x: x, y: y, DashWidth: DashWidth, DashHeight: DashHeight, colspan: colspan, rowspan: rowspan, Active: 1, CellValue: CellValue, cellClass: cellClass, previousElementSibling: previousElementSibling };
            DashboardCell.push(DashCell);

            //iterate through columns
            //columns would be accessed using the "col" variable assigned in the for loop
        }
    }
    dashboards.DashboardCell = DashboardCell;

    $.ajax({
        url: '/KPIReportAdmin/SaveDashboard',
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: { dashboards: JSON.stringify(dashboards) },
        success: function (result)
        {

        },
        error: function (result) {
            alert("Failed");
        }

    });

以下是我的课程:

public class DashboardCell
{
    public int Width { get; set; }
    public int Height { get; set; }
    public bool Active { get; set; }
    public int colspan { get; set; }
    public int rowspan { get; set; }
    public int x { get; set; }
    public int y { get; set; }
    public string CellValue { get; set; }
    public string DashCellId { get; set; }
    public string cellClass { get; set; }
    public int previousElementSibling { get; set; }
}

public class Dashboard
{
    public string Name { get; set; }
    public int Height { get; set; }
    public int Width { get; set; }
    public int UserID { get; set; }
    public List<DashboardCell> DashboardCell { get; set; }
}

我希望在SaveDashboard中收到仪表板列表,但我会得到空值

3 个答案:

答案 0 :(得分:1)

有两种方法可以使用AJAX将JS对象作为List<T>集合传递:

1)将JSON.stringify与对象本身放在一起并设置traditional: true选项,只应设置单个参数:

$.ajax({
    url: '/KPIReportAdmin/SaveDashboard',
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    traditional: true,
    data: JSON.stringify(dashboards),
    success: function (result)
    {

    },
    error: function (result) {
        alert("Failed");
    }
});

2)通过将$.param()函数与traditional: true选项一起使用来传递原始对象而不对其进行字符串化处理:

$.ajax({
    url: '/KPIReportAdmin/SaveDashboard',
    type: "POST",
    dataType: "json",
    data: $.param({ dashboards: dashboards }, true),
    success: function (result)
    {

    },
    error: function (result) {
        alert("Failed");
    }
});

发生异常是因为您传递的JS对象包含带有data: { dashboards: JSON.stringify(dashboards) }的JSON字符串,并且控制器操作方法不知道如何将其解析为List<T>集合对象作为参数。

相关问题:

Invalid JSON primitive: object

答案 1 :(得分:1)

如我所见,问题出在您的JSON文件中。在您的JSON中,您有一个名为“ DashboardName”的属性,在API中其名为“ Name”。高度,宽度,用户ID为INT,但您要向其传递的字符串。

尝试如下更改您的值

var dashboards = {
    "Name": "",
    "Width": 0,
    "Height": 0,
    "UserID": 0,
    "DashboardCell": [
    {
      "Width": 0,
      "Height": 0,
      "Active": false,
      "colspan": 0,
      "rowspan": 0,
      "x": 0,
      "y": 0,
      "CellValue: "",
      "DashCellId: "",
      "cellClass: "",
      "previousElementSibling": 0
    }
  ]
};

答案 2 :(得分:0)

我还发现,在控制器中,我正在遍历仪表板列表,在该仪表板列表中,我只需要添加Dashboard dashboards,因为该列表位于仪表板类中。

山本哲也的建议也有所帮助。

谢谢大家!