ASP.NET Core Posting Array Object JSON

假装没事ソ 提交于 2019-12-10 02:29:13

问题


I'm trying to post an array of Object in my view to my controller but params are null i saw that for just a simple object I need to put [FromBody] in my controller action.

Here is my JSON:

{
  "monJour": [
    {
      "openTime": "04:00",
      "closedTime": "21:30",
      "id": "0"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "1"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "2"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "3"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "4"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "5"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "6"
    }
  ]
}

Here is my Ajax Request :

function SendAllDay() {
    var mesJours = {};
    var monJour = [];
    mesJours.monJour = monJour;

    var senddata ='';

    $('div[id^="Conteneur"]').each(function () {
        var idDiv = $(this).attr("id");
        var jour = idDiv.substr(9, idDiv.length - 9);
        var opentps = $("#O" + jour).val();
        var closetps = $("#C" + jour).val();
        var monid = $("#id" + jour).val();

        monJour = {
            openTime: opentps,
            closedTime: closetps,
            id: monid
        }

        mesJours.monJour.push(monJour);
    });

    $.ajax({
        url: '@Url.Action("ReceiveAll")',
        dataType: 'json',
        type: 'POST',
        //data: JSON.stringify(monJours),
        data: JSON.stringify(mesJours),
        contentType:'application/json',
        success: function (response) {
            console.log('ok');
            //window.location.reload();
        },
        error: function (response) {
            console.log('error');
            //alert(response)
            //window.location.reload();
        }
    });
}

Here is my Action:

[HttpPost]
public void ReceiveAll([FromBody]ReceiveTime [] rt) { }

Here is my Class:

public class ReceiveTime
{
    public string openTime { get; set; }
    public string closedTime { get; set; }
    public string id { get; set; }
}

Any help is appreciated :)


回答1:


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.




回答2:


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.




回答3:


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();
        }
    });


来源:https://stackoverflow.com/questions/47731755/asp-net-core-posting-array-object-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!