Array of Objects (Javascript) to C# via Ajax

I have read over a lot of other people having this issue sending and array of objects to code behind C#.

Javascript

   --This constructs an array of objects called Shifts, 
   -- there is more too it but it is just how it iterates the divs for elements and such, 
   -- not important for this issue. 
   -- This is where the issue is, or I suspect in the way the data is sent and retrieved. 


Shifts = JSON.stringify({ events: Shifts });
$.ajax({
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    url: '/API/ManRoster',
    data: Shifts,
    error: function() {
        $('#info').html('<p>An error has occurred</p>');
    },
    success: function(data) {
        console.log(data);
    },
    type: 'POST'
});

console.log(Shifts);

Shifts Raw Data

{"events":[{"ShiftID":"10","EVTDate":" 2016-04-15","UID":"1","Notes":"hgr"},{"ShiftID":"10","EVTDate":" 2016-04-15","UID":"1","Notes":"hgr"},{"ShiftID":"15","EVTDate":" 2016-04-15","UID":"1","Notes":"uyuy"},{"ShiftID":"15","EVTDate":" 2016-04-15","UID":"1","Notes":"uyuy"}]}

ManRoster.cs

    [HttpPost("")]
    public JsonResult Post(List<Models.Event> events)
    {
        try
        {
            _context.Events.AddRange(events);

            return Json(true);
        }
        catch
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json("Failed");
        }
    }

Event.cs

public class Event
{
    [Key]
    public int EVTID { get; set; }

    public int UID { get; set; }
    public int ShiftID { get; set; }

    public DateTime EVTDate { get; set; }
    public string Notes { get; set; }
}

In ManRoster.cs I get 0 rows in events. So somewhere the data gets lost in the send over.

Any help on this issue would be great.

Edit 1

Changed Javascript

Shifts = JSON.stringify(Shifts);
$.ajax({
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    url: '/API/ManRoster',
    data: { events: Shifts },
    error: function() {
        $('#info').html('<p>An error has occurred</p>');
    },
    success: function(data) {
        console.log(data);
    },
    type: 'POST'
});

console.log(Shifts);

Answers 1

  • Assuming that your pre stringyfied Shifts is someting like :

    [
      {
        "ShiftID": 10,
        "EVTDate": "2016-04-15",
        "UID": 1,
        "Notes": "hgr"
      },
      {
        "ShiftID": 10,
        "EVTDate": "2016-04-15",
        "UID": 1,
        "Notes": "hgr"
      },
      {
        "ShiftID": 15,
        "EVTDate": "2016-04-15",
        "UID": 1,
        "Notes": "uyuy"
      },
      {
        "ShiftID": 15,
        "EVTDate": "2016-04-15",
        "UID": 1,
        "Notes": "uyuy"
      }
    ]
    

    You should add the [FromBody] attribute to your parameter to tell the model binder that the value come from the body :

    [HttpPost("")]
    public JsonResult Post([FromBody]List<Models.Event> events)
    {
        try
        {
            _context.Events.AddRange(events);
    
            return Json(true);
        }
        catch
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json("Failed");
        }
    }
    

    And your javascript should look like :

    Shifts = JSON.stringify(Shifts);
    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        url: '/API/ManRoster',
        data: Shifts,
        error: function () {
            $('#info').html('<p>An error has occurred</p>');
        },
        success: function (data) {
            console.log(data);
        },
        type: 'POST'
    });
    
    console.log(Shifts);
    

Related Articles