Cannot post json to controller using ajax in asp.net core

LP13 picture LP13 · Feb 9, 2018 · Viewed 8.1k times · Source

I have the following code

Controller Action Method

    [HttpPost]
    public async Task<IActionResult> Approve(int[] ids)
    {
        await _service.Approve(ids).ConfigureAwait(false);
        return Json("Success.");
    }

On client side i have the following to Post data

var data = JSON.stringify(getIDs())

   $.ajax({
        type: "POST",
        data: data,
        url: "approve",
        contentType: "application/json; charset=utf-8",
        processData: true,
        cache: false,
        })
        .done(function (response, textStatus, jqXHR) {
            // do something here
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            // do something here
        })

 function getIDs() {
        var keys = [];
         keys.push(1);
         keys.push(2);
         keys.push(3);
        return keys;
    }

ISSUE
On server, in approve action method the ids parameter is always empty.

I have also tried sending data as

var data = JSON.stringify({ids:getIDs()})

I am using ASP.NET Core with target framework 1.1.

I have the same code in classic asp.net and it works

Answer

Fernando Carvajal picture Fernando Carvajal · Feb 9, 2018

It seems that you are sending a object {ids:getIDs()} but in your controller you expect an array and you don't specific from where it will come.

Change your code like this.

[HttpPost("approve")]
public async Task<IActionResult> Approve([FromBody]Data data)
{
    await _service.Approve(data.ids).ConfigureAwait(false);
    return Json("Success.");
}

public class Data
{
    public int[] ids { get; set; }
}

or if you want you send the array direct in the Ajax POST

[HttpPost("approve")]
public async Task<IActionResult> Approve([FromBody]int[] ids)
{
    await _service.Approve(ids).ConfigureAwait(false);
    return Json("Success.");
}

Ajax...

$.ajax({
    type: "POST",
    data: JSON.stringify(getIDs()), //I assume getIDs returns an array of integers
    url: "/approve",
    contentType: "application/json; charset=utf-8",
    processData: true,
    cache: false,
})