提问人:Muhammad Rifqi 提问时间:8/31/2023 更新时间:9/4/2023 访问量:55
无法获取从 AJAX 传递到我的 API 控制器的 searchValue、orderColumn、orderDirection
Can't get the searchValue, orderColumn, orderDirection that passed from the AJAX into my API controllers
问:
因此,为了获取数千个数据集并使用 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”:“一个 或更多验证错误 occurred.“,”status“:400,”traceId“:”00-245b7bb81d09c2a78a230e2a25c28a19-90e9f86d60626f3b-00“,”errors“:{”orderColumn“:[”这 orderColumn 字段为必填字段“],”searchValue“:[”searchValue 字段 是必需的.“],”orderDirection“:[”orderDirection 字段是 必需。“]}}
我的 AJAX 代码无法读取 searchValue、orderColumn 或 orderDirection 值,因此无法将它们传递给 API。
有什么建议吗?
答:
0赞
Tiny Wang
9/1/2023
#1
我有一个如下代码的测试,我认为我们可以在发送ajax请求之前获得所需的参数。以避免我们无法获取参数的情况。
[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 中还是 in,它们都成为查询字符串并最终附加到 url 中。你能帮忙检查一下你这边的请求吗?data
评论