[英]Passing a string array from JS to C# controller
我在 JS 中有一个数组 ( var selectedEmails = [];
) 在我从网格中收集选定的电子邮件后,我将 GET 调用到 C# controller:
$.ajax({
type: 'GET',
url: '@Url.Action("SendEmailBatchs", "account")',
data: { emails: selectedEmails },
contentType: 'application/json',
success: (data) => {
console.log("data", data);
}
})
调用时,C#中的参数取不到数据。 我已经签入 JS,电子邮件在数组中。 使用断点,我已经确认调用了 Controller 的方法:
Controller:
[HttpGet("sendemailbatchs")]
public async Task<ActionResult> SendEmailBatchs(string[] emails)
{
...
foreach (ApplicationUser user in users)
{
await SendEmailConfirmation(user);
}
return Ok;
}
将数据更改为data: { emails: JSON.stringify(selectedEmails) },
将传递一个仅包含 1 个元素的数组,其中包含一个字符串化的电子邮件列表"[\"loes.vea@phanc.com\",\"MaAlonso.Mfizer.com\",\"cech@mll-int.cm\",\"jier.aris@si.com\"]"
JS 的正确参数是什么,以便我得到一个字符串 ARRAY,其中每个 email 都是数组的一个元素?
emails = [0]: "loes.vea@phanc.com\",
[1]: \"MaAlonso.Mfizer.com\", ...
您在 controller 中期望的内容与您通过 ajax 调用发送的内容之间存在差距。
public async Task<ActionResult> SendEmailBatchs(string[] emails)
让我们了解一下上面 function 的参数,您期望的是一个字符串数组,并将在 function 正文中将其称为电子邮件。 因此,您必须在请求正文中传递一个字符串数组。
PFB我简单的controller和对应的ajax调用:
[HttpGet("api/test")]
public ActionResult<int> RecieveData(string[] emails)
{
return emails.Count();
}
像这样从 UI 调用:
var settings = {
"url": "https://localhost:5000/api/test",
"method": "GET",
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify([
"john@example.com",
"jane@example.com"
]),
};
$.ajax(settings).done(function (response) {
console.log(response);
});
所以,在遵循Devesh的建议后,我得到了
var settings = {
"url": '@Url.Action("SendEmailBatchs", "account")',
"method": "GET",
"headers": {
"Content-Type": "application/json"
},
"data": {
emails: JSON.stringify(selectedEmails)},
};
问题仍然存在,因为我需要在 C# 中反序列化结果:
public async Task<ActionResult> SendEmailBatchs(string emails)
{
var selectedEmails = JsonConvert.DeserializeObject<string[]>(emails);
//DO STUFF
}
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.