简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM