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

195
Visualizações
Converting a dynamic Variable to List<model> or array

I want to send this Array with Ajax to api :

var receipt = Array();

        receipt = [
            { 'Service': 'Saab', 'Order': '20' },
            { 'Service': 'Volvo', 'Order': '12' },
            { 'Service': 'BMW', 'Order': '25' }
        ];

And this is my Ajax body :

var r = JSON.stringify(receipt);
        
        $.ajax({
            type: "POST",
            dataType: "Json",
            contentType: "application/json; charset=utf-8",
            data: r,
            url: "api/Receipt",
            success: function (result) {
                // To Do
                console.info(result);
            },
            error: function (result) {
                console.info(result);
            }
        });

And this is what i get as Json :

        {[
            {
               "Service": "Saab",
               "Order": "20"
            },
            {
               "Service": "Volvo",
               "Order": "12"
             },
             {
               "Service": "BMW",
               "Order": "25"
              }
          ]}

And i catch them in api side Like this :

[Route("api/Receipt")]
    [WebMethod]
    public string Receipt_Turn(object obj)
    {
        dynamic dyn = JsonConvert.DeserializeObject(obj.ToString());

        if (dyn != null)
        {
            return dyn[1].ToString();
        }
        else
        {
            return "false";
        }

    }

And it works, the part return dyn[1].ToString() returns second record of my Array. But i want to convert this dynamic variable to a list or array of a model .

Here is my model :

[Serializable()]
    public class Receipt
    {
        public string Service { get; set; }
        public string Order { get; set; }
    }

I want to act with it like this :

string serv = receipt[1].Service;

How can i do it ?

Thanks...

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Delete the Array Part in Your JS Script and Write it Like this :

var receipt = [
            { 'Service': 'Saab', 'Order': '20' },
            { 'Service': 'Volvo', 'Order': '12' },
            { 'Service': 'BMW', 'Order': '25' }
        ];

in this shape you are sending an Object. in your code i guess you are sending an JArray So it Will make some Problems in Converting from JArray to another Type .

in your API Side , Edit Your Code As Below :

public string Receipt_Turn(object r)
    {

        //important Line Here
        List<Receipt> rr = JsonConvert.DeserializeObject<List<Receipt>>(r.ToString());

        if (rr != null)
        {
            return rr[1].ToString();
        }
        else
        {
            return "false";
        }

    }

as you can see, we get it Like an Object and then we will be able to Get Ready your DeserializeObject part Like i mentioned.

you most declare a List of your Model, and after part DeserializeObject add that Type You want to Convert it to.

here Cause we Declared List<Receipt> , we should convert our DeserializeObject to it, so we add <List<Receipt>> after DeserializeObject.

and Finally you can use it Like You wish .

string serv = rr[1].Service;
over 4 years ago · Santiago Trujillo Relatório

0

Assuming you are using .NET Core, it should be able to bind it automatically if you do something like this:

```
[Route("api/Receipt")]
[WebMethod]
public string Receipt_Turn(List<Receipt> receipts)
{

    if (receipts != null)
    {
        return "seomthing";
    }
    else
    {
        return "false";
    }
}
```
over 4 years ago · Santiago Trujillo 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