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

How to send a list of int from Javascript (Ajax) to C#? - Stack Overflow

programmeradmin0浏览0评论

normaly I would write

 $.ajax({
            url: '@Url.Action("PlantHistoryContent", "PlantStatus")',
            data: {id: 1},
            async: false,
            type: "POST"
        })

when I want to pass the integer id to server side in C#:

public void PlantHistoryContent(int id)
{
 ///
}

How to do the same with a list of integer?

So I have a object-list of unkown length and want to pass it as a list to server side?

My server side should be

public void PlantHistoryContent(List<int> id)
{
 ///
}

How to write the ajax call data parameter to this?

normaly I would write

 $.ajax({
            url: '@Url.Action("PlantHistoryContent", "PlantStatus")',
            data: {id: 1},
            async: false,
            type: "POST"
        })

when I want to pass the integer id to server side in C#:

public void PlantHistoryContent(int id)
{
 ///
}

How to do the same with a list of integer?

So I have a object-list of unkown length and want to pass it as a list to server side?

My server side should be

public void PlantHistoryContent(List<int> id)
{
 ///
}

How to write the ajax call data parameter to this?

Share Improve this question asked Nov 9, 2015 at 14:17 Rene KochRene Koch 3373 silver badges13 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

A list in JavaScript looks like:

var list = [ 1, 2, 3, 4 ];

To build it you can do:

var list = [];
list.push(1);
list.push(2);
list.push(3);
list.push(4);

Then when you send it you can do:

$.ajax({
    url: '@Url.Action("PlantHistoryContent", "PlantStatus")',
    data: { ids: list },
    async: false,
    type: "POST"
})

or

$.ajax({
    url: '@Url.Action("PlantHistoryContent", "PlantStatus")',
    data: { ids: [ 1, 2, 3, 4 ] },
    async: false,
    type: "POST"
})

By default form-encoding is used. The request body will look like:

ids[0]=1&ids[1]=2&ids[2]=2&ids[3]=3

With form-encoding there is no way to know what the type of the parameter is. They're all strings.

If you use JSON as your transfer encoding instead you can send integers because JSON knows string and ints and list etc.

$.ajax({
    url: '@Url.Action("PlantHistoryContent", "PlantStatus")',
    data: { data: JSON.stringify({ ids: [ 1, 2, 3, 4 ] }) },
    async: false,
    type: "POST"
})

Now your request body looks like:

data=%5B1%2C2%2C3%2C4%5D

For some one who may searching same problem like above. If you still cannot find any idea from other answers. I got the same issue, and here is my solution: just simple add [FromBody] to controller action

public void PlantHistoryContent([FromBody]List<int> id)
{
    //
}
发布评论

评论列表(0)

  1. 暂无评论