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 badges2 Answers
Reset to default 4A 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
版权声明:本文标题:How to send a list of int from Javascript (Ajax) to C#? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745276735a2651232.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论