Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

547
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!