You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法将AJAX传递的searchValue等参数传入ASP.NET API控制器的问题

解决方案

1. 修复AJAX请求的data函数

核心问题是你的data函数只修改了参数对象但没有返回,导致自定义参数(orderColumn、orderDirection、searchValue)没有发送到服务器。同时,DataTables的order.column是列索引,不是实体字段名,需要映射为实际的Product属性名:

"ajax": {
    url: "https://localhost:7174/API/products/GetServerData",
    type: "GET",
    dataType: "json",
    data: function (d) {
        // 按你的DataTables列配置,映射索引到Product字段名
        const columnFieldMap = {
            0: "Id",
            1: "Name",
            // 其他列按实际配置添加
        };
        
        var order = d.order[0] || {};
        // 返回处理后的参数对象
        return {
            draw: d.draw || 1,
            start: d.start || 0,
            length: d.length || 10,
            searchValue: d.search?.value || '',
            orderColumn: columnFieldMap[order.column] || '',
            orderDirection: order.dir || 'asc'
        };
    },
    dataSrc: "data"
},

2. 调整API参数允许空值

ASP.NET Core的ApiController会自动验证简单类型参数,默认不允许空值。将参数改为可空类型,避免空参数触发400错误:

[HttpGet("GetServerData")]
public ActionResult GetServerData(int draw, int start, int length, string? searchValue, string? orderColumn, string? orderDirection)
{
    var query = _context.Products.AsQueryable();

    // 应用搜索过滤
    if (!string.IsNullOrEmpty(searchValue))
    {
        query = query.Where(p => p.Name.Contains(searchValue));
    }

    // 应用排序
    if (!string.IsNullOrEmpty(orderColumn) && !string.IsNullOrEmpty(orderDirection))
    {
        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));
        }
    }

    // 修正recordsFiltered:返回过滤后的总记录数,不是原始总数
    int totalRecords = _context.Products.Count();
    int filteredRecords = query.Count();

    // 分页处理
    var records = query.Skip(start).Take(length).ToList();

    var response = new
    {
        draw,
        recordsTotal = totalRecords,
        recordsFiltered = filteredRecords,
        data = records
    };

    return Ok(response);
}

3. 可选:显式允许空字符串(若需严格验证)

如果不想用可空类型,可给参数添加[Required(AllowEmptyStrings = true)]属性,明确允许空字符串:

public ActionResult GetServerData(int draw, int start, int length, 
    [Required(AllowEmptyStrings = true)] string searchValue, 
    [Required(AllowEmptyStrings = true)] string orderColumn, 
    [Required(AllowEmptyStrings = true)] string orderDirection)

内容的提问来源于stack exchange,提问作者Muhammad Rifqi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 07:55:37