从 URL.Action 发送数组并在控制器中获取空值
Sending array from URL.Action and getting null in controller
我有一个函数,在 for 循环中添加项目后,通过发送 arr
参数(数组)的操作 URL 调用控制器,我看到它发送数据但出现空值在控制器参数中。我想知道哪里出了问题?
Javscript 函数
function Submit() {
QRCodeval.forEach((code) => arr.push(code.innerHTML));
window.location.href = "@Url.Action("ReceivedFromBarCode","PurchaseOrder")?" +arr;
}
Link 由控制器生成:
http://localhost:56978/PurchaseOrder/ReceivedFromBarCode?JJJKP,RRPRQ,PPLQR
我在 arr 参数中得到 null 的控制器。
public async Task<ActionResult> ReceivedFromBarCode(string[] arr)
{
return View();
}
MVC 模型绑定器期望数组以下列格式传递:arr=value1&arr=value2&...
您可以使用 map()
和 join()
创建正确的格式。但是您还需要对这些值进行编码,因为它们是 URL 中的参数。 encodeURIComponent
可以提供帮助:
let urlParams = array.map((val) => {
return `arr=${encodeURIComponent(val)}`
}).join('&');
window.location.href = "@Url.Action("ReceivedFromBarCode","PurchaseOrder")?"
+ urlParams;
并将 urlParams
附加到您的 URL。以下代码段中的示例输出:
let array = ["value1", "http://example.com?x=1", "<script>alert('')</sctipt>"];
let urlParams = array.map((val) => {
return `arr=${encodeURIComponent(val)}`
}).join('&');
console.log(urlParams);
我有一个函数,在 for 循环中添加项目后,通过发送 arr
参数(数组)的操作 URL 调用控制器,我看到它发送数据但出现空值在控制器参数中。我想知道哪里出了问题?
Javscript 函数
function Submit() {
QRCodeval.forEach((code) => arr.push(code.innerHTML));
window.location.href = "@Url.Action("ReceivedFromBarCode","PurchaseOrder")?" +arr;
}
Link 由控制器生成:
http://localhost:56978/PurchaseOrder/ReceivedFromBarCode?JJJKP,RRPRQ,PPLQR
我在 arr 参数中得到 null 的控制器。
public async Task<ActionResult> ReceivedFromBarCode(string[] arr)
{
return View();
}
MVC 模型绑定器期望数组以下列格式传递:arr=value1&arr=value2&...
您可以使用 map()
和 join()
创建正确的格式。但是您还需要对这些值进行编码,因为它们是 URL 中的参数。 encodeURIComponent
可以提供帮助:
let urlParams = array.map((val) => {
return `arr=${encodeURIComponent(val)}`
}).join('&');
window.location.href = "@Url.Action("ReceivedFromBarCode","PurchaseOrder")?"
+ urlParams;
并将 urlParams
附加到您的 URL。以下代码段中的示例输出:
let array = ["value1", "http://example.com?x=1", "<script>alert('')</sctipt>"];
let urlParams = array.map((val) => {
return `arr=${encodeURIComponent(val)}`
}).join('&');
console.log(urlParams);