Reputation: 53
I have a JQGrid which I am trying to have load dynamic JSON data (depending on search results). It seems my problem is that I can't get the JSON string in the correct format.
Here's my code:
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);
}
}
and in my view:
<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'
});
});
How can I use the data I'm getting back (from SQL server in the form of a DataSet) and load it into the grid. Assume the columns are formatted correctly (they are). I checked JSONLint and my json is definitely not valid, but I don't know how to fix it.
Thanks in advance.
Upvotes: 0
Views: 3142
Reputation: 4283
It seems that you are serializing the row data twice. Once in the GetJson
function, and again when the Json result is created.
I would try returning a List<Dictionary<string, object>>
from the GetJson function, and let Json(jsonData)
do the serializing.
Upvotes: 1