因此,为了获取数千个数据集并使用ajax获取数据,我尝试将数据表服务器端集成到我的API中。
这是我的 API 代码
[HttpGet("GetServerData")]
public ActionResult GetServerData(int draw, int start, int length, string searchValue, string orderColumn, string orderDirection)
{
var query = _context.Products.AsQueryable();
//Apply filtering based on searchValue
if (!string.IsNullOrEmpty(searchValue))
{
query = query.Where(p => p.Name.Contains(searchValue));
}
// Apply sorting
if (!string.IsNullOrEmpty(orderColumn) && !string.IsNullOrEmpty(orderDirection))
{
// Assuming orderColumn is a valid property name
var propertyInfo = typeof(Product).GetProperty(orderColumn);
if (propertyInfo != null)
{
query = orderDirection == "asc"
? query.OrderBy(p => propertyInfo.GetValue(p, null))
: query.OrderByDescending(p => propertyInfo.GetValue(p, null));
}
}
// Count the total number of records before paging
int totalRecords = query.Count();
// Apply paging
query = query.Skip(start).Take(length);
var records = query.ToList();
var response = new
{
draw,
recordsTotal = totalRecords,
recordsFiltered = totalRecords, // You might modify this based on your filtering logic
data = records
};
return Ok(response);
}
这是我的 AJAX 请求,
"ajax": {
url: "https://localhost:7174/API/products/GetServerData",
type: "GET",
dataType: "json",
data: function (d) {
d.draw = d.draw || 1;
d.start = d.start || 0;
d.length = d.length || 10; // Records per page
d.search = d.search || {};
d.search.value = d.search.value || '';
var order = d.order[0] || {};
d.orderColumn = order.column || '';
d.orderDirection = order.dir || '';
d.searchValue = d.search.value || ''; // Ensure that searchValue is included
},
dataSrc: "data"
},
这就是错误出现的地方
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"一 或更多验证错误 发生。","status":400,"traceId":"00-245b7bb81d09c2a78a230e2a25c28a19-90e9f86d60626f3b-00","errors":{"orderColumn":[" orderColumn 字段是必需的。"],"searchValue":["searchValue 字段 为必填项。"],"orderDirection":["orderDirection 字段为 必需。"]}}
我的 AJAX 代码无法读取 searchValue、orderColumn 或 orderDirection 值,因此它们无法传递到 API。
有什么建议吗?
我用如下代码进行了测试
[HttpGet]
public IActionResult GetServerData(int start, int length, string searchValue) {
string a = "{\"res\":\"success\",\"searchValue\":\""+ searchValue + "\"}";
return Ok(a);
}
$("#GetServerData").click(function () {
$.ajax({
url: "https://localhost:7041/home/GetServerData",//?length=10&start=0&searchValue=keywords
type: "get",
dataType: "json",
data:{
start:1,
length:2,
searchValue:"asdf"
},
success: function (data) {
alert(data.res);
}
})
})
无论我将数据放在 url 中还是
data
中,它们都会成为查询字符串并最终附加到 url 中。您能帮忙检查一下您那边的要求吗?