ASP.NET Core Posting Array Object JSON

江枫思渺然 提交于 2019-12-05 03:42:33

Instead of using ReceiveTime[] rt, it might be better to model the data according to the same structure that you POST. For example, you could create a class that looks like this:

public class MesJours
{
    public ReceiveTime[] MonJour { get; set; }
}

I don't know if MesJours makes sense as a class name (I don't speak French), but the idea is still clear - You can name the class whatever you like.

Given this, you could update your controller like this:

[HttpPost]
public void ReceiveAll([FromBody] MesJours mesJours)
{
    // Access monJour via mesJours.
    var rt = mesJours.MonJour;
}

This would satisfy the ASP.NET MVC Model Binder and should give you the data you've POSTed. This also has the added benefit of easily accommodating any additional properties you might want to POST.

Florinache

The name in the ajax js request needs to coincide with the name of the parameter from the backend controller.

Try updating the method signature in the controller as follows:

public void ReceiveAll([FromBody]ReceiveTime [] monJour)

Also, even though I like the french language, I would like to suggest to you to use english for naming variables. Please don't be offended in anyway but it's really recommended.

1.Add a class, Mesjours:

public class MesJours
{
    public ReceiveTime[] MonJour { get; set; }
}   

2.And in controller action change the return type to async Task(for aspnetcore)

[HttpPost]
public async Task<IActionResult> ReceiveAll([FromBody]MesJours mesJourData)
{
    var rt = mesJourData.MonJour;
}

3.in the view, make sure data posted has the same name as the parameter in the controller action (in this case mesJourData). Take note of the syntax of line containing data parameter in the ajax method

$.ajax({
        url: '@Url.Action("ReceiveAll")',
        dataType: 'json',
        type: 'POST',
        data:{mesJourData: mesJours} ,
        contentType:'application/json',
        success: function (response) {
            console.log('ok');
            //window.location.reload();
        },
        error: function (response) {
            console.log('error');
            //alert(response)
            //window.location.reload();
        }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!