0
\$\begingroup\$

I want to know whether I am following the best practices of using jquery datatable with .net core.

In Controller

private async Task<DTResult<RoleViewModel>> GetDataTableResult(DTParameters parameters)
    {
        try
        {
            var users = _roleManager.Roles.Select(r => new RoleViewModel { Id = r.Id, Name = r.Name }).AsNoTracking();

            int totalCount;
            IQueryable<RoleViewModel> filter;

            string searchparam = parameters.Search.Value.Trim();

            if (!string.IsNullOrEmpty(searchparam) && !string.IsNullOrWhiteSpace(searchparam))
            {
                Expression<Func<RoleViewModel, bool>> search =
                    x => (x.Name ?? "").IndexOf(searchparam, StringComparison.OrdinalIgnoreCase) >= 0;


                totalCount = users.Count(search);
                users = users.Where(search);
                users = SortByColumnWithOrder(parameters.Order[0].Column, parameters.Order[0].Dir.ToString(), users);
                filter = users.Skip(parameters.Start).Take(parameters.Length);
            }
            else
            {
                totalCount = users.Count();
                users = SortByColumnWithOrder(parameters.Order[0].Column, parameters.Order[0].Dir.ToString(), users);
                filter = users.Skip(parameters.Start).Take(parameters.Length);
            }

            var result = new DTResult<RoleViewModel>
            {
                Draw = parameters.Draw,
                Data = await filter.ToListAsync(),
                RecordsFiltered = totalCount,
                RecordsTotal = totalCount
            };
            return result;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private static IQueryable<RoleViewModel> SortByColumnWithOrder(int order, string orderDirection, IQueryable<RoleViewModel> data)
    {
        try
        {
            switch (order)
            {
                case 2:
                    return orderDirection.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.Name) : data.OrderBy(p => p.Name);
                default:
                    return data.OrderByDescending(p => p.Name);
            }
        }
        catch (Exception)
        {
            return data;
        }
    }

        [HttpPost("RolesDataHandler")]
    public async Task<IActionResult> RolesDataHandler([FromBody]DataTableParameters parameters)
    {
        try
        {
            return Ok(await GetDataTableResult(parameters));
        }
        catch (Exception ex)
        {
            return Json(new { error = ex.Message });
        }
    }

In View

        var table = $("#roleDataTable").DataTable({
        "serverSide": true,
        "ajax": {
            "url": "@Url.Action("RolesDataHandler")",
            "type": "POST",
            "contentType": "application/json; charset=utf-8",
            "data": function(data) {
                return JSON.stringify(data);
            },
            "error": function(xhr) {
                var response = JSON.parse(xhr.getResponseHeader('X-Responded-JSON'));

            }
        },
        "processing": true,
        "paging": true,
        "deferRender": true,
        "columnDefs": [
            {
                "searchable": false,
                "orderable": false,
                "targets": 0,
                "visible": false,

            },
            { "width": "22%", "targets": 2 }
        ],
        "columns": [
            { "data": "id" },
            { "data": "name" },

        ],
        "order": [1, "asc"]
    });
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.