Json jqGrid绑定错误

时间:2015-01-12 07:08:46

标签: json jqgrid

在我的mvc代码中,我将datatable转换为json。
我的json的结果格式正确,但它没有填充我的jqgrid。

json结果:

"{\"total\":2,\"page\":1,\"records\":2,\"rows\":[{\"id\":1,\"cell\":[\"1\",\"TEST
 ACCOUNT\",\"TEST LOB\",\"TEST REPORT\"]}]}"

代码:

public string JsonForJqgrid(DataTable dt, int pageSize, int totalRecords, int page)
    {
        int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("{");
        jsonBuilder.Append("\"total\":" + totalPages + ",\"page\":" + page + ",\"records\":" + (totalRecords) + ",\"rows\"");
        jsonBuilder.Append(":[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{\"id\":" + (i+1) + ",\"cell\":[");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
        jsonBuilder.Append("}");
        return jsonBuilder.ToString();
    }

jqGrid:

$("#jqTable").jqGrid({
        // Ajax related configurations
        url: "Staffing/LOBStaffing",
        datatype: "json",
        mtype: "GET",
        // Specify the column names
        colNames: ["ID", "Account", "Lob", "Report"],

        // Configure the columns
        colModel: [
            { name: "ID", index: "ID", width: 40, align: "center", key: true, hidden: true },
            { name: "Account", width: 150, align: "center" },
            { name: "Lob", width: 150, align: "center" },
            { name: "Report", width: 150, align: "center" }
        ],
        rowNum: 10,
        loadonce: true,
        viewrecords: true,
        sortorder: "desc",
        caption: "List Staffing Details"
        //gridview: true,
        //scrollOffset: 0
    });

控制器操作:

[HttpGet]
    public JsonResult LOBStaffing()
    {
        string sJson = _staffing.JsonForJqgrid(_staffing.GetStaffing(), 1, 2, 1);

        return Json(sJson, JsonRequestBehavior.AllowGet);
    }

1 个答案:

答案 0 :(得分:1)

我在项目中使用的一种方法是将数据填充到这些类中:

public class Row
{
    public string id { get; set; }
    public List<string> cell { get; set; }

    public Row()
    {
        cell = new List<string>();
    }
}

public class JqgridData
{
    public int page { get; set; }
    public int total { get; set; }
    public int records { get; set; }
    public List<Row> rows { get; set; }

    public JqgridData()
    {
        rows = new List<Row>();
    }
}

您的方法JsonForJqgrid应该返回JqgridData结构,允许您存储动态数据,因为您可以根据需要在Row中添加尽可能多的字符串。控制器中的Json()方法将此类序列化为jqgrid的正确方法。

如果您不仅要存储DataTimeDecimalTypes字符串,还可以尝试在dynamic属性中使用public List<string> cell类型。但我没有检查它是如何运作的。