admin管理员组

文章数量:1418346

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)
{
    //
}

本文标签: How to send a list of int from Javascript (Ajax) to CStack Overflow