0

I'm attempting to pass paginated results from a Web API to an MVC application and displaying in the View using DataTable. While I've successfully retrieved the data from the server and transmitted it to the MVC controller, which then forwards it to the View, I'm encountering issues displaying the data in the DataTable.

ASP.net MVC Controller's method for reading the API endpoint:

public async Task<IActionResult> Index(int page = 1, int pageSize = 10, string search = "", string category = "")
{
    var query = $"?page={page}&pageSize={pageSize}&search={search}&category={category}";
    var url = string.Format("{0}Country/", _baseUrl);
    var countryData = new CountryResponse();

    using (var httpClient = new HttpClient())
    {
        using (var response = await httpClient.GetAsync(url + query))
        {
            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                countryData = JsonConvert.DeserializeObject<CountryResponse>(json);

                if (countryData is null)
                    return NotFound();

                if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
                {
                    // Format data for DataTable AJAX request
                    return Json(new
                    {
                        draw = Request.Form["draw"].FirstOrDefault(), // Get draw parameter from DataTables
                        recordsTotal = countryData.TotalItemsCount,
                        recordsFiltered = countryData.TotalItemsCount,
                        data = countryData.Items
                    });
                }

                return View(countryData);
            }
        }
    }

    return View(countryData);
}

Here is the Ajax function:

<script>
    $(document).ready(function () {
        $('#countriesTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: {
                url: '@Url.Action("Index", "Country")',
                type: 'GET',
                dataSrc: 'data'
            },
            columns: [
                {
                    data: null,
                    render: function (data, type, row, meta) {
                        return meta.row + 1;
                    }
                },
                { data: 'Id' },
                { data: 'CountryName' },
                { data: 'ISO2' },
                { data: 'ISO3' },

            ]
        });
    });
</script>

My code is only rendering the table headers, as shown below. What am I doing wrong?

enter image description here

Thanks

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.