JQGrid动态数据加载(JSON)

时间:2013-11-04 18:43:07

标签: jquery asp.net-mvc json jqgrid html-helper

我有一个JQGrid,我试图加载动态JSON数据(取决于搜索结果)。看来我的问题是我无法以正确的格式获取JSON字符串。

这是我的代码:

public ActionResult GridData(string sidx, string sord, int page, int rows)
    {

        DataSet data = (DataSet) TempData["temp"];


        //var rowdata = GetJson(data.Tables[0]);
        var jsonData = new
        {
            total = data.Tables[0].Rows.Count,
            page = page,
            records = data.Tables[0].Rows.Count,
            rows = GetJson(data.Tables[0])
        };
        var a = Json(jsonData, JsonRequestBehavior.AllowGet);
        return a;

    }

    public string GetJson(DataTable dt)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row = null;

        foreach (DataRow dr in dt.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in dt.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            rows.Add(row);
        }
        return serializer.Serialize(rows);
    }

}

在我看来:

<script type="text/javascript">
jQuery(document).ready(function(){ 
  jQuery("#list").jqGrid({
    url:'/Search/GridData/',
    datatype: 'json',
    mtype: 'GET',
    colNames: @Html.Raw(formatColNames()),
    colModel:@Html.Raw(formatColModel()),
    pager: jQuery('#pager'),
    rowNum:10,
    rowList:[5,10,20,50],
    viewrecords: true,
    caption: 'My first grid'
  }); 
}); 

如何使用我正在返回的数据(从SQL Server以DataSet的形式)并将其加载到网格中。假设列格式正确(它们是)。我检查了JSONLint,我的json绝对无效,但我不知道如何解决它。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您似乎正在将行数据序列化两次。进入GetJson函数后,再次创建Json结果时。

我会尝试从GetJson函数返回List<Dictionary<string, object>>,让Json(jsonData)进行序列化。