最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot post json to controller using ajax in asp.net core - Stack Overflow

programmeradmin2浏览0评论

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 and it works

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 and it works

Share Improve this question asked Feb 9, 2018 at 0:34 LP13LP13 34.2k61 gold badges259 silver badges460 bronze badges 5
  • 2 You are not defining [FromBody] Attribute in your action parameter and it wont work unless you pass them as query (very bad practice on Http requests other than GET). Or you have to send it as a form (multipart/form-data mime type) – Tseng Commented Feb 9, 2018 at 0:51
  • @Tseng adding [FromBody] worked. Thank You. However i did not understand your statement and it wont work unless you pass them as query (very bad practice on Http requests other than GET). I have HttpPost attribue defined on the action method and from client side as well i am using ajax POST so i am assuming data will be send in the body not as query parameter.. am i missing something? (I only missed [FromBody] attribute because i think in classic ASP.NET this wasn't needed) – LP13 Commented Feb 9, 2018 at 4:26
  • ....and as per the jQuery documentation if processData is true then "data is converted to a query string, if not already a string".. so in my case i am doing JSON.stringify()..so data is of type string. So i data will be send in the body and not in the query string. isn't that correct? – LP13 Commented Feb 9, 2018 at 5:02
  • If anyone interested..Here is why ASP.NET Core needs FromBody andrewlock/model-binding-json-posts-in-asp-net-core – LP13 Commented Feb 9, 2018 at 5:19
  • Read the docs please learn.microsoft./en-us/aspnet/core/mvc/models/model-binding. Basically when you have no [FromBody] attribute, it tries to read the parameter values from routes (in url) from query (url after question mark? or from form (on post requests with multipart/form-data) – Tseng Commented Feb 9, 2018 at 7:00
Add a ment  | 

1 Answer 1

Reset to default 6

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 e.

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,
})
发布评论

评论列表(0)

  1. 暂无评论