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

ASP.NET MVC项目中jqGrid无法加载数据库数据求助

解决jqGrid无法加载ASP.NET MVC返回数据的问题

我帮你排查了代码里的几个关键问题,这些应该就是导致数据无法显示的核心原因:


1. 错误地将对象序列化为JSON字符串传递给jqGrid

你在AJAX的done回调里,把已经被jQuery自动解析为JavaScript对象数组的result,又用JSON.stringify()转成了字符串。但jqGrid的data参数需要的是原生JS对象数组,而非JSON字符串——这会直接导致jqGrid无法识别数据结构。

2. ColModel的index字段与数据字段不匹配

你的colModel配置里,bid列的index设为了branch_id,name列的index设为了branch_name,但你的数据里对应的字段是bid和name。index属性需要和数据字段名(或列的name属性)保持一致,否则jqGrid无法正确映射数据列。

3. 可选:老版本jqGrid与高版本jQuery的兼容性问题

Trirand的jqGrid 4.4.4是2012年的老版本,而jQuery 3.3.1是2018年的版本,两者可能存在兼容性问题。如果前面的修改后仍有异常,可以考虑降级jQuery到1.x版本(比如1.12.4),或者升级jqGrid到开源分支free-jqGrid(支持新jQuery版本)。


修改后的代码示例

修正AJAX回调与UpdateGrid函数

$(document).ready(function(){
    $.ajax({
        url: "UpdateData",
        method: "GET"
    }).done(function (result) {
        // 直接传递jQuery解析好的对象数组,无需JSON.stringify
        console.log(result);
        UpdateGrid(result);
    });
});

function UpdateGrid(result){
    $("#jqGridTable").jqGrid({
        datatype: "array",
        colNames: ["User ID", "Code", "Name", "Request Sent At"],
        colModel: [
            { name: "user_id", index: "user_id", align: 'center' },
            // 修正index为数据字段名bid
            { name: "bid", index: "bid", align: 'center' },
            // 修正index为数据字段名name
            { name: "name", index: "name", align: 'center' },
            { name: "queue_req_time", index: "queue_req_time", align: 'center' }
        ],
        data: result, // 直接传入对象数组
        rowNum: 20,
        rowList: [10, 20, 30],
        gridview: true,
        caption: "Waiting in Queue",
        loadonce: true,
        pager: "#jqGridPagerDiv",
        loadError: function (xhr, status, error) {
            console.log("Error details:", xhr.responseText, status, error);
            alert("Load error: " + error);
        },
        loadComplete: function (data) {
            alert("Load complete, total rows: " + $(this).jqGrid('getGridParam', 'records'));
        }
    });
}

补充验证Element类的构造函数

你代码里的Element类定义是无参的,但创建实例时用了new Element(user_id, bid, name, queue_req_time),请确保类有对应的构造函数:

public class Element{ 
    public string bid { get; set; } 
    public string user_id { get; set; } 
    public string name { get; set; } 
    public string queue_req_time { get; set; } 

    // 添加匹配的构造函数
    public Element(string userId, string bid, string name, string queueReqTime)
    {
        user_id = userId;
        this.bid = bid;
        this.name = name;
        queue_req_time = queueReqTime;
    }
}

验证步骤

  1. 运行项目后打开浏览器控制台(F12),确认AJAX请求成功返回数据且无报错。
  2. 查看loadComplete弹出的提示,确认显示了正确的行数。
  3. 如果仍无数据,检查jqGrid的列宽是否足够,或是否有CSS样式导致内容被隐藏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:05:43