javascript - 如何将类型对象的 json 数组传递给 MVC Controller 类

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

我正在尝试将 JSON 数组传递到我的 Controller 。我希望能够将数据从 JSON 数组发布到数据库,该数组通过客户端的 javascript 填充并传递到 Controller 。但是,它没有在 Controller 中接收任何内容。我的 Controller 收到一个空值作为参数。

以下是我的 Controller :

  [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");
        }

    });

以下是我的类(class):

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 中收到仪表板列表,但我得到的是 null

最佳答案

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

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 字符串。并且 Controller 操作方法不知道如何将其解析为 List<T>集合对象作为参数。

相关问题:

Invalid JSON primitive: object

关于javascript - 如何将类型对象的 json 数组传递给 MVC Controller 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54436867/

相关文章:

javascript - ExtJS button2 onClick 通过组件执行点击button1

javascript - 单独进入那个div时显示<div>

c# - 在 .NET Xml 序列化中,是否可以使用基于属性值的不同标记对具有枚举属性的类进行序列化?

C# 隐式数组声明

arrays - 添加数组中的长度或每个字符串并创建一个附加结果的新数组

javascript - 菜单滚动也会滚动背景屏幕

c# - 给定边界矩形、起始角和扫角,如何确定圆弧端点

c# - 如何在 1D 数组中使用 "flatten"或 "index"3D 数组?

javascript - 拼接改变我的初始数组

javascript - 密码强度计