关于 ASP.net + JQuery + JQGrid + JSON.net 的简单应用(二)
代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>评论管理</title>
<!-- 引入主题文件 -->
<link rel="stylesheet" type="text/css" media="screen" href="../themes/redmond/jquery-ui-1.8.4.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="../themes/ui.jqgrid.css" />
<!-- 引入脚本文件 -->
<script type="text/javascript" src="../scripts/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../scripts/jQuery/plugins/jquery-ui-1.8.4.custom.min.js"></script>
<script type="text/javascript" src="../scripts/jQuery/plugins/grid.locale-cn.js"></script>
<script type="text/javascript" src="../scripts/jQuery/plugins/jquery.jqGrid.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
jQuery("#list").jqGrid({
url: 'asynchronous/GridData.ashx?p=Comment',
datatype: "json",
height: 'auto',
colNames: ['评论ID', '类别ID', '文章ID', '留言人', '留言内容', '发布日期', '留言IP'],
colModel: [
{ name: 'CommentID', index: 'CommentID', sorttype: "int", width: 60 },
{ name: 'TypeID', index: 'TypeID', sorttype: "int", width: 60 },
{ name: 'FromID', index: 'FromID', sorttype: "int", width: 60 },
{ name: 'Name', index: 'Name', editable: true, width: 60 },
{ name: 'Contents', index: 'Contents', sortable: false, width: 300 },
{ name: 'PublishDate', index: 'PublishDate', sorttype: "date", width: 190 },
{ name: 'IP', index: 'IP', align: "right", sorttype: "float", editable: true, width: 130 }
],
viewrecords: true,
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'CommentID',
jsonReader: {
root: "griddata",
total: "totalpages",
page: "currpage",
records: "totalrecords",
repeatitems: false
},
pager: "#pager",
caption: "评论管理",
sortorder: "desc",
hidegrid: false
});
jQuery("#list").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false });
});
</script>
</head>
<body>
<form id="frmMComment" runat="server">
<div>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"><!--用于数据显示-->
</table>
<div id="pager" class="scroll" style="text-align: center;"><!--用于分页的层-->
</div>
</div>
</form>
</body>
</html>
客户端的完整代码是这样的,注意,在下面的body部分有两个层,分别是绑定GRID和绑定PAGER用的哦!
3.handler.ashx的处理
关键应该就是这个东西了,我直接贴重要代码,大家直接粘贴进去就好了,这里的算法是根据官网的PHP改过来的,可能不是很严谨,或者有什么bug,欢迎大家指正或者帮忙想出更好的算法.
代码
<%@ WebHandler Language="C#" Class="GridData" %>
using System;
using System.Web;
using System.Data;
using Wood8.Common;
using Wood8.DataAccess.SQLServer;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Web.Services;
using System.Collections;
using System.Collections.Generic;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class GridData : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
context.Response.Buffer = true;
context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
context.Response.AddHeader("pragma", "no-cache");
context.Response.AddHeader("cache-control", "");
context.Response.CacheControl = "no-cache";
context.Response.ContentType = "text/plain";
DataTable dt;
string jsonData=string.Empty;
string sPage = HttpContext.Current.Request.Params["page"].ToString(); //当前请求第几页
int iPage = int.Parse(sPage);
string sLimit = HttpContext.Current.Request.Params["rows"].ToString(); //grid需要显示几行
int iLimit = int.Parse(sLimit);
string sSidx = HttpContext.Current.Request.Params["sidx"].ToString(); //按什么排序
string sSord = HttpContext.Current.Request.Params["sord"].ToString(); //排序方式('desc'/'asc')
if(sSidx=="")
{
sSidx ="1";
}
int iTotalpages;
SQLComment sc = new SQLComment();
DataSet sResult = sc.getAllComments();
int iCount = sResult.Tables[0].Rows.Count;
if( iCount >0 )
{
int iR = iCount/iLimit;
iTotalpages = iR + 1;
}
else
{
iTotalpages = 0;
}
if (iPage > iTotalpages)
{
iPage = iTotalpages;
}
int iStart = iLimit * iPage - iLimit + 1; // do not put iLimit*(iPage - 1)
iLimit = iLimit * iPage;
sResult = sc.getCommentsFromTo(iStart, iLimit, sSidx, sSord, iPage);
dt = sResult.Tables[0];
string totalpages = iTotalpages.ToString();
string currpage = iPage.ToString();
string totalrecords = iCount.ToString();
IsoDateTimeConverter idtc = new IsoDateTimeConverter();
idtc.DateTimeFormat = "yyyy-MM-dd hh:mm:ss ffffff";
jsonData = JsonConvert.SerializeObject(dt, idtc).ToString();
string returnData = string.Empty;
returnData = "{";
//总共多少页
returnData += "\"totalpages\"";
returnData += ":";
returnData += "\"";
returnData += totalpages;
returnData += "\"";
returnData += ",";
//当前第几页
returnData += "\"currpage\"";
returnData += ":";
returnData += "\"";
returnData += currpage;
returnData += "\"";
returnData += ",";
//总共多少记录
returnData += "\"totalrecords\"";
returnData += ":";
returnData += "\"";
returnData += totalrecords;
returnData += "\"";
returnData += ",";
//datable转换得到的JSON字符串
returnData += "\"griddata\"";
returnData += ":";
returnData += jsonData;
returnData += "}";
context.Response.Write(returnData);
}
public bool IsReusable {
get {
return false;
}
}
}
OK,这里重点又来了,我这里使用到了JSON.net来将查询出来的datatable转换成JSON的格式newtonsoft的JSON.net也是开源的,所以不用担心,官网的更新速度也还比较快,文档也比较充裕,大家可以去官网找找:
http://james.newtonking.com/default.aspx
我这里就只用到了简单的将datatable转换成JSON.
(p.s.这里很多引用都没用的,因为我是个完整的项目,只截取了部分,大家看到引用没有用的就删掉就OK啦~)