I have read this post
I'm moving from MVC .Net Core to Blazor. I'm using Datatable with MVC but I want to reuse it. But I'm using ajax function from datatable. Here the JS code:
function AddDataTable(elementName, controller, columns, columnDefs, actionMethod = "/Search") {
var table = $(elementName).DataTable(
{
"lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
"searching": true,
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": true,
"pageLength": 10,
"pagingType": "simple_numbers",
"ajax": {
"url": controller + actionMethod,
"type": "POST",
"datatype": "json",
"error": function (xhr, error, thrown) {
if (xhr.status === 405) {
window.location.href = urlBase + "StatusCode/" + xhr.status;
}
return EmptyTable(elementName, controller, columns, columnDefs);
},
},
"columns": columns,
"columnDefs": columnDefs
}
);
return table;
}
API (C# .Net Core)
[HttpPost]
[Route("Datatable")]
public IActionResult Search(string start, string length, string sortColumn, string sortColumnDir, string searchValue, string draw = null)
{
try
{
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
var list= _context.Entity;
if (!(string.IsNullOrEmpty(sortColumn) && !string.IsNullOrEmpty(sortColumnDir)))
{
list= list.OrderBy(sortColumn + " " + sortColumnDir);
}
List<Entity> data;
if (!string.IsNullOrEmpty(searchValue))
{
list= list.Where(m => m.property.Contains(searchValue));
recordsTotal = list.Count();
}
else
{
recordsTotal = list.Count();
}
data = list.Skip(skip).Take(pageSize).ToList();
return Ok(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });
}
catch (Exception ex)
{
return Conflict();
}
}
In my Blazor APP I moved script and implemented the code in this post it works but it first call all my data and then only filter, sort and search but in client side. I want implement a way to call it from Blazor
Actually on my Blazor app just call Datatable in this way:
protected async override Task OnAfterRenderAsync(bool firstRender)
{
await JSRuntime.InvokeAsync<string>("AddDataTable", new object[] { "#" + id + " table", Searchable });
await base.OnAfterRenderAsync(firstRender);
}
My script in Blazor App
function AddDataTable(table, searching) {
$(table).DataTable({
"searching": searching
});
}
There is a way to reuse it?