Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

324
Visualizações
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\", ...
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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);
});
about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda