gpt4 book ai didi

javascript - 将 int 数组传递给 MVC Controller

转载 作者:行者123 更新时间:2023-12-02 17:21:20 26 4
gpt4 key购买 nike

我有一个 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 吗?

接收发生在 Controller 中:

public async Task<ActionResult> Filter(int[] locations, int[] machines, int[] severities, int[] messages)
{
//TODO filter
}

这被调用但参数为空;

刚开始时,我使用了它,它适用于单个值,但需要扩展到数组。

var url = '@Url.Action("Filter", "ActiveMessages")' + '?locations=' + locations + '&machines=' + machines + '&severities=' + severities + '&messages=' + messages;

最佳答案

发布操作的最佳实践是使用正文发送发布参数(注意参数的 [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) {
}});
}

关于javascript - 将 int 数组传递给 MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42417746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com