我有一个JavaScript函数,我传递4个数组,每个数组都是这种类型
[1,2]只有int值或[],里面没有值。这些被传递到Url.Action
命令。
function Filter(locations, machines, severities, messages) {
var url = '@Url.Action("Filter", "ActiveMessages")?' + $.param({
locations: locations, machines: machines, severities: severities, messages: messages });
$.ajax({
url: url,
method: 'POST',
traditional: true,
success: function (data) { }
});
}
我尝试使用$.param()
构建参数。但这并没有产生我期待的参数,我得到这样的结论:"/ActiveMessages/Filter?locations%5B%5D=1"
我也尝试过这样做:
decodeURIComponent($.param({ locations: filterlocations, machines: filtermachines, severities: filterseverities, messages: filtermessages }))
然后我得到这样的东西:
"/ActiveMessages/Filter?locations[]=1&locations[]=2"
有没有其他方法可以将这样的数组解析为url?
接收在控制器中发生:
public async Task<ActionResult> Filter(int[] locations, int[] machines, int[] severities, int[] messages)
{
//TODO filter
}
这会被调用,但参数为null;
当我开始使用时,我使用的是单个值但需要扩展到数组。
var url = '@Url.Action("Filter", "ActiveMessages")' + '?locations=' + locations + '&machines=' + machines + '&severities=' + severities + '&messages=' + messages;
答案 0 :(得分:1)
后期操作的最佳做法是使用正文发送帖子的参数(注意参数的[FromBody]注释):
[HttpPost]
public async Task<ActionResult> Filter([FromBody] int[] locations, [FromBody] int[] machines, [FromBody] int[] severities, [FromBody] int[] messages)
需要在ajax调用的主体中指定参数:
function Filter(locations, machines, severities, messages) {
var url = '@Url.Action("Filter", "ActiveMessages")';
$.ajax({
url: url,
method: 'POST',
data: JSON.stringify({ locations: locations, machines: machines, severities: severities, messages: messages }),
traditional: true,
success: function (data) {
}});
}
答案 1 :(得分:1)
var locations = [1,2];
var machines = [3,4];
var severities = [5,6];
var messages = [7,8];
$.ajax({
url: @Url.Action("Filter", "ActiveMessages"),
method: 'POST',
data: {
locations: locations,
machines: machines,
severities: severities,
messages: messages
},
success: function (data) {
}
});
在这种情况下,不需要字符串化:)
答案 2 :(得分:0)
尽管其他人说的是完全正确的(为此而生),但有时还是有选择的。您的查询存在的问题是,必须为每个数组值重复使用关键字machines=
(或位置等)。这样的事情会起作用:
const machines = [1, 2];
const locations = [3, 4];
function formatParamArray(array, name) {
return `${name}=` + array.reduce((acc, cur) => `${acc}&${name}=${cur}`);
}
var url = '@Url.Action("Filter", "ActiveMessages")?'+formatParamArray(machines, 'machines')+'&'+formatParamArray(locations, 'locations');