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

117
Visualizações
Get an array of objects from a Razor page with JavaScript/jQuery

I am developing an asp.net core web app. I am sending data from a razor page to getJson script to display a chart on the page. When I'm sending an array of anonymous classes, getJson receives data. When I'm sending an array of custom class, getJson receives an array of empty objects that have no properties.
Received OK:

            var anonymousarray = new[]
                {
                    new {name = "first", value = 3 },
                    new {name = "second", value = 6 },
                    new {name = "third", value = 1 },
                };

Received as an array of empty objects:

            Test[] testarray = new []
            {
                new Test {name = "first", value = 3},
                new Test {name = "second", value = 6},
                new Test {name = "third", value = 1}
            };

Test class:

    public class Test
    {
        public int value;
        public string name;
    }

Handler on Razor page:

        public JsonResult OnGetData()
        {
            Test[] testarray= new[]
            {
                new Test {name = "first", value = 3},
                new Test {name = "second", value = 6},
                new Test {name = "third", value = 1}
            };
            
            return new JsonResult(testarray);
        }

Razor page script:

@section scripts{
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script>
        var ctx = document.getElementById('barChart').getContext('2d');
        $(function () {
            $.getJSON(`?handler=Data`, (data) => {
                var labels = [];
                var dataresults = [];
                $.each(data, function (index, item) {
                    labels.push(item.name);
                    dataresults.push(item.value);
                });
                console.log(labels)
                console.log(dataresults)
                var myChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: 'Results',
                            data: dataresults,
                            borderWidth: 1
                        }]
                    },
                    options: {
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            });
        });
    </script>
}

Please help me to send an array/list of my custom classes to getJson script. I spent many hours reading articles and posts but could not find a solution.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When I'm sending an array of anonymous classes, getJson receives data. When I'm sending an array of custom class, getJson receives an array of empty objects that have no properties.

Please try to modify your Test class to define value and name as property with get and set accessor, like below.

 public class Test
    {
        public int value {get;set;};
        public string name {get;set;};
    }

From this doc about "Serialization behavior", you can find:

  • Fields are ignored.
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