我已经用一个类实现了 Kendo Grid 分页。但现在我试图将它与动态列 SQL 表分页绑定,问题是在第二个滚动/页面上,它失败了方法
var data = dt.ToDataSourceResult(request);
data.Data
为空
这是完整的代码
剃须刀页面
@model System.Data.DataTable
@(Html.Kendo().Grid<dynamic>()
.Name("Grid")
.Sortable()
.Scrollable(sc => sc.Endless(true))
.Filterable()
.Groupable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(100)
.Model(model =>
{
var id = "Id";
model.Id(id);
})
.Read(read => read.Action("Data_Read", "DynamicColumn"))
)
)
控制器
public IActionResult Data_Read([DataSourceRequest] DataSourceRequest request)
{
var dt = GetViewsData(request.PageSize, request.Page);
var data = dt.ToDataSourceResult(request);
var viewData = new DataSourceResult()
{
Data = data.Data, //this return NULL on the second page/scroll request
Total = 181480 //total rows of table, just make it static
};
return Json(viewData);
}
public DataTable GetViewsData(int pageSize, int page)
{
try
{
int offSet = (page - 1) * 100;
string connString = "Server=.; Database=TheVault_VMC; Trusted_Connection=true; MultipleActiveResultSets=True; Encrypt=False;";
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand("sp_GetData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@OFFSetRows", offSet);
cmd.Parameters.AddWithValue("@PageSize", pageSize);
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataAdapter.FillSchema(dataTable, SchemaType.Mapped);
con.Close();
return dataTable;
}
catch (Exception ex)
{
throw ex;
}
}
}
数据库存储过程
CREATE PROCEDURE [dbo].[sp_GetData]
@OFFSetRows INT,
@PageSize INT
As
BEGIN
SELECT Id, [Column1], [Column2], [Column3],[Column4],[Column5],[Column6]
FROM
[StagingDetail]
ORDER BY Id
OFFSET @OFFSetRows ROWS
FETCH NEXT @PageSize ROWS ONLY
END
问题是函数 ToDataSourceResult() 在第二个请求时返回 NULL 数据
var data = dt.ToDataSourceResult(request);
var viewData = new DataSourceResult()
{
Data = data.Data,
Total = 181480
};
知道我在这里做错了什么吗?
我找到了解决方案,将Datatable转换为动态Array,然后将其传递给DataSourceResult()类的数据。
public IActionResult Data_Read([DataSourceRequest] DataSourceRequest request)
{
var dt = GetViewsData(request.PageSize, request.Page);
var arr = ToDynamic(dt);
var viewData = new DataSourceResult()
{
Data = arr,
Total = 181480
};
return Json(viewData);
}
private static List<dynamic> ToDynamic(DataTable dt)
{
var dynamicDt = new List<dynamic>();
foreach (DataRow row in dt.Rows)
{
dynamic dyn = new ExpandoObject();
dynamicDt.Add(dyn);
foreach (DataColumn column in dt.Columns)
{
var dic = (IDictionary<string, object>)dyn;
dic[column.ColumnName] = row[column];
}
}
return dynamicDt;
}