我已经读过这个post
我正在从MVC .Net Core转到Blazor。我在MVC中使用Datatable,但是我想重用它。但是我正在使用datatable中的ajax函数。这是JS代码:
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核心)
[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();
}
}
在我的Blazor APP中,我移动了脚本并在此post中实现了代码,该脚本可以工作,但是它首先调用我的所有数据,然后仅在客户端进行过滤,排序和搜索。我想实现一种从Blazor调用它的方法
实际上,在我的Blazor应用程序中,只需通过以下方式调用Datatable:
protected async override Task OnAfterRenderAsync(bool firstRender)
{
await JSRuntime.InvokeAsync<string>("AddDataTable", new object[] { "#" + id + " table", Searchable });
await base.OnAfterRenderAsync(firstRender);
}
我在Blazor App中的脚本
function AddDataTable(table, searching) {
$(table).DataTable({
"searching": searching
});
}
有一种方法可以重用吗?