繁体   English   中英

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

[英]How to pass a json array of type object to MVC controller class

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

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

1)将JSON.stringify与对象本身放在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字符串data: { dashboards: JSON.stringify(dashboards) }并且控制器操作方法不知道如何将其解析为List<T>集合对象作为参数。

相关问题:

无效的JSON原语:object

如我所见,问题出在您的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 } ] }; 

我还发现,在控制器中,我正在遍历Dashboard dashboards列表,在该仪表板列表中,我只需要添加Dashboard dashboards板即可。

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

感谢大家!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM