Home > Mobile >  ASP.NET Core C# Jquery Datatable Error: Unexpected token
ASP.NET Core C# Jquery Datatable Error: Unexpected token

Time:11-05

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

CodePudding user response:

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.

CodePudding user response:

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>
  • Related