简体   繁体   中英

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:

 $.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. I've checked in JS, and the emails are in the array. Using breakpoints, I've confirmed the Controller's method is getting called:

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\"]"

What would be the correct parameter from JS so that I get a string ARRAY where each email is an element of the array?

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.

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. So, you will have to pass an array of strings in the request body.

PFB my simple controller and corresponding ajax call:

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

Call from UI like this:

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

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#:

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

Thx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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