Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

552
Vistas
ASP.NET Core C# Jquery Datatable Error: Unexpected token

I want to fill a jquery datatable by passing an array to it, the controller pass an array of users using ViewBag as following:

userInfo[] users = _context.userInfo.ToArray();
ViewBag.UsersArray = users;

In the view, I used ViewBag.UsersArray as a data source for the jquery datatable:

<script>
    $(document).ready(function () {
        $('#users').DataTable({
            data: @ViewBag.UsersArray,
            columns: [
                { data: 'id' },
                { data: 'username' },
                { data: 'balance' },
                { data: 'contract_id' }
            ]
        });
    });
</script>

I always got Unexpected token ']' enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

To use C# objects in script tags in Razor pages, you must first convert them to JSON. Razor does not do this automatically.

This way you can easily serialize your array to JSON:

<script>
    $(document).ready(function () {
        $('#users').DataTable({
            data: @Json.Serialize(@ViewBag.UsersArray),
            columns: [
                { data: 'id' },
                { data: 'username' },
                { data: 'balance' },
                { data: 'contract_id' }
            ]
        });
    });
</script>
about 4 years ago · Juan Pablo Isaza Denunciar

0

The problem seems to just be that the array is being treated as a reference to an object rather than being enumerated. I would first try wrapping @ViewBag.UsersArray in quotes, and if that makes no difference I would "manually" enumerate through the array in your JS code and add each array element to the table's data property.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda