简体   繁体   English

JS传一个字符串数组给C# controller

[英]Passing a string array from JS to C# controller

I have an array in JS ( var selectedEmails = []; ) After I collect the selected Emails from a grid, I call a GET 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);
            }
        })

When called, the parameter in C# gets no data.调用时,C#中的参数取不到数据。 I've checked in JS, and the emails are in the array.我已经签入 JS,电子邮件在数组中。 Using breakpoints, I've confirmed the Controller's method is getting called:使用断点,我已经确认调用了 Controller 的方法:

Controller: Controller:

[HttpGet("sendemailbatchs")]
 public async Task<ActionResult> SendEmailBatchs(string[] emails)
        {
            ...
            foreach (ApplicationUser user in users)
            {
                await SendEmailConfirmation(user);
            }
            return Ok;
        }

Changing the data to data: { emails: JSON.stringify(selectedEmails) }, will pass an array with 1 element only, containing a stringified list of emails "[\"loes.vea@phanc.com\",\"MaAlonso.Mfizer.com\",\"cech@mll-int.cm\",\"jier.aris@si.com\"]"将数据更改为data: { emails: JSON.stringify(selectedEmails) },将传递一个仅包含 1 个元素的数组,其中包含一个字符串化的电子邮件列表"[\"loes.vea@phanc.com\",\"MaAlonso.Mfizer.com\",\"cech@mll-int.cm\",\"jier.aris@si.com\"]"

What would be the correct parameter from JS so that I get a string ARRAY where each email is an element of the array? JS 的正确参数是什么,以便我得到一个字符串 ARRAY,其中每个 email 都是数组的一个元素?

emails = [0]: "loes.vea@phanc.com\",
[1]: \"MaAlonso.Mfizer.com\", ...

There is a gap between what you are expecting in the controller and what you are sending through ajax call.您在 controller 中期望的内容与您通过 ajax 调用发送的内容之间存在差距。

public async Task<ActionResult> SendEmailBatchs(string[] emails)

Let's understand the parameter of the above function, you are expecting an array of strings and will refer to it as emails in the function body.让我们了解一下上面 function 的参数,您期望的是一个字符串数组,并将在 function 正文中将其称为电子邮件。 So, you will have to pass an array of strings in the request body.因此,您必须在请求正文中传递一个字符串数组。

PFB my simple controller and corresponding ajax call: PFB我简单的controller和对应的ajax调用:

[HttpGet("api/test")]
public ActionResult<int> RecieveData(string[] emails)
{
     return emails.Count();
}

Call from UI like this:像这样从 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);
});

so, after following Devesh 's suggestions I ended up with所以,在遵循Devesh的建议后,我得到了

var settings = {
    "url": '@Url.Action("SendEmailBatchs", "account")',
    "method": "GET",
    "headers": {
        "Content-Type": "application/json"
    },
    "data": {
        emails: JSON.stringify(selectedEmails)},
    };

the issue persisted, because I needed to DESERIALIZE the result, in C#:问题仍然存在,因为我需要在 C# 中反序列化结果:

public async Task<ActionResult> SendEmailBatchs(string emails)
{
    var selectedEmails = JsonConvert.DeserializeObject<string[]>(emails);
    //DO STUFF
}

Thx谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM