对象数组在MVC核心控制器中总是空的

本文关键字:控制器 数组 MVC 核心 对象 | 更新日期: 2023-09-27 18:13:06

我试图张贴一个简单的对象数组到我的MVC核心控制器Frombody属性,但出于某种原因,它来为空。如果我只发布一个对象,它会工作得很好,这是我的代码:

$(document).ready(function() {
    var tk = new Array();
    $("#calendar").fullCalendar({
        header: {
            left: 'prevYear,prev,next,nextYear',
            center: 'title',
            right: 'month,agendaWeek,agendaDay',
        },
        defaultView: 'month',
        editable: true,
        alldayslot: false,
        selectable: true,
        slotminutes: 15,
        nextDayThreshold: "00:00:00",
        events: "/Home/FullCalendar",
        eventDrop: function(event, delta, revertFunc)
        {
            Update(event);
        },
    });
    function Update(event) {
        var datarow =
            {
                "id": event.id, 
                "start": event.start,
                "end": event.end,
            }
        tk.push(datarow);
        debugger;
        confirm(("Save changes?"))
        console.log(JSON.stringify(datarow));
        $.ajax({
            type: "post",
            dataType: 'json',
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(tk),
            url: '@Url.Action("JSON", "Home")',
            success: function (data) {
                debugger;
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                debugger;
            }
        });
    }
});

My Controller class

[HttpPost]
public IActionResult UpdateTask([FromBody] List<Task_fullcal> td)
{
    // Do something
    // td is always null if passed as an array 
    //td working fine if passed as single value
}

对象数组在MVC核心控制器中总是空的

我也遇到过同样的问题,我花了几个小时才弄清楚。我把解写在

通过jQuery AJAX传递对象数组给控制器,动作数据在ASP中总是空的。.NET Core 2.2 MVC -它与。NET Framework 4.5一起工作

遵循以下:


我在。net Core 3.1中工作,这对我有用:

1。控制器

<尝试strong> [FromForm] 而不是 [FromBody]

    [HttpPost]
    public ActionResult CreateOrdersPOSTObject([FromForm] List<T_POS_ENT_ORDER_DETIALS_Temp> prm)
    {
        //your logic...
        return Json(new { msg = "Successfully added " });
    }

2。AJAX调用

JSON.stringfy()contentType都不应该使用。

            var DATA = [];
            DATA.push({ LocPrice: "12", LocProductID: "1002", discount: "0", posNumber: "1", productName: "soap", productQynt: "1" });
            DATA.push({ LocPrice: "23", LocProductID: "1003", discount: "0", posNumber: "1", productName: "shampoo", productQynt: "1" });
            DATA.push({ LocPrice: "7",LocProductID: "1004" ,discount: "0",posNumber: "2" ,productName: "sponge",productQynt: "2"});
            $.ajax({
                url: '@Url.Content("~/home/CreateOrdersPOSTObject")',
                data: { "prm": DATA },
                type: "POST",
                dataType: "json",
                async: true
            });

或者如果您愿意,也可以使用简写的$。post使用相同的结果

            var DATA = [];
            DATA.push({ LocPrice: "12", LocProductID: "1002", discount: "0", posNumber: "1", productName: "soap", productQynt: "1" });
            DATA.push({ LocPrice: "23", LocProductID: "1003", discount: "0", posNumber: "1", productName: "shampoo", productQynt: "1" });
            DATA.push({ LocPrice: "7",LocProductID: "1004" ,discount: "0",posNumber: "2" ,productName: "sponge",productQynt: "2"});
            $.post(
                '@Url.Content("~/home/CreateOrdersPOSTObject")',
                { "prm": DATA },
                function () {
                  alert( "success" );
                })
              .fail(function() {
                alert( "error" );
              });

在您的操作中删除FromBody,对于复杂类型的请求将在请求体中包含复杂类型。尝试使用邮差和尝试不同的选项。

1在URL中传递对象,使用[FromUri]

2在body中传递对象,移除FromBody

3传递简单的值,如字符串,使用[FromUri]如果你想从URL

访问在请求体中传递简单的值,如字符串,使用[FromBody]

在我的例子中,我将其转换为视图中的JSON字符串:

var seatsJson = JSON.stringify(seats);

然后,在动作中,我使用Newtonsoft将其强制转换为对象数组:

var seats = JsonConvert.DeserializeObject<SeatsModel[]>(seatsjson);