How it works > Read data for the table

Crud Elite

Getting Started

Action Column

Hide action column

Add buttons to action column

Table functions

Default sorting

“Show 10 records” drop-down

The “Search…” placeholder

Exported file

Columns ordering

Custom content in a column

Confirm delete popup

Common issues

Edit auratheme.table.js

Other

Clone for another table

How it works

Read data for the table

How is the code reading data to display on the table?


The code below is how to include a table in a page.

<div id="@ViewBag.TableId" class="position-relative" 
		data-loadtable="@Url.Action("GetPartialViewListing", "Home")"
		data-filename="@ViewBag.Title"
		data-table-sort="" data-table-size="" data-table-search="" data-table-pg="">
    @await Html.PartialAsync("_TableLengthAndSearch", new TableLengthViewModel { Options = TableHelper.DefaultPageSizeOptions, SearchPlaceholder = ClientTableConfig.SearchMessage })
    @await Html.PartialAsync("_LoadingTable")
</div>

In /wwwroot/js/auratheme.table.js, we have the code below that will get all the div with data-loadtable attribute. Then, read the data based on the URL for data-loadtable in the loadData function. getTableActionsObject will get the data-table-sort, data-table-size, data-table-search and data-table-pg attached to that div.

//get all the div with data-loadtable
const loadTables = document.querySelectorAll('div[data-loadtable]');
loadData(table.getAttribute("data-loadtable"), getTableActionsObject(table), table.id);

function getTableActionsObject(renderDiv) {
    var attributes = renderDiv.attributes;
    var tableActionsObject = {};
    for (var i = 0; i < attributes.length; i++) {
        if (attributes[i].name.indexOf('data-table') === 0) {
            var attributeName = attributes[i].name.replace('data-table-', '');
            tableActionsObject[attributeName] = attributes[i].value;
        }
    }
    return tableActionsObject;
}
function loadData(loadTableUrl, searchFilterParams, tableId) {
    fetch(loadTableUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(searchFilterParams)
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(data => {
            document.querySelector(`#${tableId} .toRenderTable`).innerHTML = data;
        })
        .catch(error => {
            console.error('There was a problem with the fetch operation:', error);
        })
        .finally(() => {
            //do something finally
        });
}

In HomeController.cs, we have the code below that will accept the sort, size, search and page and process the reading of the records.

[HttpPost]
public async Task<IActionResult> GetPartialViewListing([FromBody] dynamic requestData)
{
    try
    {
        string sort = requestData.sort?.Value ?? "";
        int? size = (int.TryParse(requestData.size.Value, out int parsedSize)) ? parsedSize : null;
        string search = requestData.search?.Value ?? "";
        int? pg = (int.TryParse(requestData.pg.Value, out int parsedPg)) ? parsedPg : 1;

        List<ColumnHeader> headers = new List<ColumnHeader>();
        if (string.IsNullOrEmpty(sort))
        {
            sort = ClientTableConfig.DefaultSortOrder;
        }
        headers = TableHelper.GetColumnHeaders(ClientTableConfig.DefaultColumnHeaders, sort);
        var list = ReadRecords();//This will generate the query to read the records
        list = ClientTableConfig.PerformSearch(list, search);//Query to perform search
        list = ClientTableConfig.PerformSort(list, sort);//Query to further perform sort
        ViewData["CurrentSort"] = sort;
        ViewData["CurrentPage"] = pg ?? 1;
        ViewData["CurrentSearch"] = search;
        int? total = list.Count();
        int? defaultSize = ClientTableConfig.DefaultPageSize;
        size = size == 0 || size == null ? (defaultSize != -1 ? defaultSize : total) : size == -1 ? total : size;
        ViewData["CurrentSize"] = size;
        
        //the query will generate paginated list here
        PaginatedList<ClientViewModel> result = await PaginatedList<ClientViewModel>
            .CreateAsync(list, pg ?? 1, size.Value, total.Value, headers, ClientTableConfig.SearchMessage);
        
        //pass the data to this partial view and render the data inside the <table> of this partial view
        return PartialView($"~/Views/{viewFolder}/_Table.cshtml", result);
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, $"{GetType().Name} - {MethodBase.GetCurrentMethod()?.Name} Method");
    }
    return PartialView("~/Views/Shared/Error.cshtml", null);
}

public IQueryable<ClientViewModel> ReadRecords()
{
    var result = from t1 in _db.Clients.AsNoTracking()
                 orderby t1.Name
                 select new ClientViewModel
                 {
                     Id = t1.Id,
                     Name = t1.Name,
                     EmailAddress = t1.EmailAddress,
                     Notes = t1.Notes
                 };
    return result;
}