Jqgrid可以接受的数据源格式通常是local、json、string等,而我们通过MVC Controller查询数据库(Linq)通常转化为tolist(),例如:
public object Res(string Sort = null, int OrderBy = 3, int PageNumber = 0, int PageSize = 0)
{
var stu = (from p in db.Student orderby p.Age
select p).Skip((PageNumber-1) * PageSize).Take(PageSize);
return ObjectExtentions.ToJsonString(stu.ToList());
//return stu.ToList();
}
由于jqgrid需要接受json类型的,所以我们需要转化list类型为json类型
public static class ObjectExtentions
{
/// <summary>
/// 为Oject对象增加ToJsonString方法(注意对项目添加Newtonsoft.Json.dll引用)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJsonString(this Object obj)
{
JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
return JsonConvert.SerializeObject(obj, jsSettings);
}
}
前台代码为:
$(document).ready(function () {
//ChangeTime();
$("#TB").jqGrid({
url: '../Student/Res',
datatype: 'json',
height: 160,
scrollOffset: 0,
mtype: "GET",//提交方式
rowNum: 2,
rowList: [2, 5, 10],
colNames: ["Name", "Sex","Age","Tel","Edit"],
colModel: [
{ index: "Name", name: "Name",sorttype:"text" },
{ index: "Sex", name: "Sex", sorttype: "text" },
{ index: "Age", name: "Age", sorttype: "text" },
{ index: "Tel", name: "Tel", sorttype: "text",key:true },
{ index: "Name",name:"Name", formatter: function (cellvalue, options, rowObject) { return "<center><input type='button' style='100px' onclick=Test(this) title='" + rowObject.Name + "' value='" + rowObject.Name + "' /></center>" } }
//{ index: "id", name: "id", formatter: function (cellvalue, options, rowObject) { return "<center><input type='button' onclick=Test(this) title='" + rowObject.Name + "' value='" + rowObject.Name + "' /></center>" } },
],
"865",
//caption: "Resources",
gridview: true,
loadonce:false,
cmTemplate:
{
sortable: true
},
sortname: "Age",
sortorder: "desc",
pager: "#gridPager1",
jsonReader: {
root: "rows",
page: "pageindex",
total: "pagecount",
records: "total",
id: "0"
},
prmNames: {
search: "Search",
page: 'PageNumber',
rows: 'PageSize',
sort: 'OrderBy',
order: 'Sort',
id: 'RequestID'
},
viewrecords: true,
pgbuttons: true,
loadtext:"Wait Loading",
gridComplete: function () {
//var ids = jQuery("#TB").jqGrid("getDataIDs");
//for (var i = 0; i < ids.length; i++) {
// var id = ids[i];
// modify = "<a href=\"#\" style=\"color:#f60\" onclick=\"Delete(" + id + ")\">Delete</a>";
// jQuery("#TB").jqGrid("setRowData", id, { operDel: modify });
//}
},
onSelectRow: function (rowid, status, e) {
alert(rowid);
var rowDatas = $("#TB").jqGrid('getRowData', rowid);
alert(rowDatas["Sex"]);
}
});
});
</script>
<!DOCTYPE html>
<html>
<body>
<div>
<table id="TB">
</table>
<div id="gridPager1">
</div>
</div>
</body>
</html>