首页 > 解决方案 > 如何从 Ajax 将具有多个值的 json 对象发布到控制器

问题描述

我有这个 Ajax 帖子为单个值工作,但我需要它来处理多个值。我错过了什么?

我已经尝试将公共类“Value”设为 List AND Guid[]。我试图将方法参数调整为 List AND Value[]。不知道还有什么可以尝试的。

Class:
public class Value
{
    public Guid TimeId { get; set; }
}

Method:
public IActionResult ApproveAllTimesheets([FromBody]Value information)

View JS:
function SubAll() {
        var selectedValues = $('#timesheet').DataTable().column(0).checkboxes.selected().toArray();

        var instructions = {};
        for (var TimeId in selectedValues) {
            instructions[TimeId] = { TimeId: selectedValues[TimeId] };
        }

        var inst = JSON.stringify(instructions);

        $.ajax({
            url: "/Admin/ApproveAllTimesheets",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: inst,
            success: function (result) {
                alert(result);
            },
            error: function (xhr, textStatus) {
                if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
                else {
                    alert('Content load failed!', "info");
                }
            }
        });
    };

如果我通过这个对象发送它可以工作,但我需要像我的 ajax 帖子那样发送多个值。

var指令= {时间ID:“13246578-1234-7894-4562-456789123456”};

更新#1 我通过扩展类找到了一个适合我的结构,现在我只需要弄清楚如何创建正确的对象和数组组合。

New Classes:
public class ValueContainer
{
    public List<Value> MasterIds { get; set; }
}

public class Value
{
    public Guid TimeId { get; set; }
}

Method:
 public IActionResult ApproveAllTimesheets([FromBody]ValueContainer information)

Structure I need now (this works hard coded):
 var jsonObject = {
            "MasterIds": [{ TimeId: "13246578-1234-7894-4562-456789123450" }, { TimeId: "13246578-1234-7894-4562-456789123451" }, { TimeId: "13246578-1234-7894-4562-456789123452" }]
        };

我对这些东西还是新手,但我看到的是 jsonObject 是一个带有键“MasterIds”的对象,相应的值是一个带有键“TimeId”的对象数组......这是一个正确的评估吗? .以及如何在代码中创建它?

标签: asp.net-mvcasp.net-coreasp.net-ajaxjavascript-objects

解决方案


您需要创建一个对象数组,然后将其设置在容器对象中:

 var instructions = []; // an array 
    for (var i = 0; i < selectedValues.length; i++) {
        instructions.push({ TimeId: selectedValues[i] };
    }

var Value = {TimeId: instructions}; // creating object with property TimeId as array of guid

var inst = JSON.stringify(Value);
.......
....... your ajax code

并且您的类属性也应该是数组类型:

public Guid[] TimeId { get; set; }

推荐阅读