本文介绍了的jqGrid不显示数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经创建的jqGrid和ASP.net客户端和服务器端。网格显示,但没有数据。我看不到结果。网格显示,但没有数据。
服务器端
编码
使用系统;
使用System.Collections.Generic;
使用System.Collections.ObjectModel;
使用System.Data这;
使用System.Data.SqlClient的;
使用的System.Web;
使用System.Web.Script.Serialization; 样本空间
{
公共结构JQGridResults
{
公众诠释页;
公众诠释总量;
公众诠释记录;
公共JQGridRow []的行; }
公共结构JQGridRow
{
公众诠释身份证;
公共字符串[]细胞;
} [Serializable接口]
公共类用户
{
公众诠释用户名
{搞定;组; } 公共字符串用户名
{搞定;组; } 公共字符串名字
{搞定;组; } 公共字符串中间名
{搞定;组; } 公共字符串姓氏
{搞定;组; } 公共字符串EMAILID
{搞定;组; }
///<总结>
///为jqgridhandler摘要说明
///< /总结>
公共类jqGridHandler:IHttpHandler的
{ 公共无效的ProcessRequest(HttpContext的背景下)
{
HTT prequest请求= context.Request;
HTT presponse响应= context.Response; 字符串_search =请求[_搜索];
字符串numberOfRows =请求[行];
字符串的PageIndex =请求[页];
字符串sortColumnName =请求[SIDX];
字符串sortOrderBy =请求[SORD];
INT总记录;
收藏<使用者>用户= GetUsers(numberOfRows,PageIndex的,sortColumnName,sortOrderBy,出总记录);
字符串输出= BuildJQGridResults(用户,Convert.ToInt32(numberOfRows),Convert.ToInt32(PageIndex的),Convert.ToInt32(总记录));
RESPONSE.WRITE(输出);
} 私人字符串BuildJQGridResults(集合<使用者>的用户,INT numberOfRows,诠释的PageIndex,INT总记录)
{ JQGridResults结果=新JQGridResults();
清单< JQGridRow>行=新的List< JQGridRow>();
的foreach(在用户使用的用户)
{
JQGridRow行=新JQGridRow();
row.id = user.UserID;
row.cell =新的字符串[6];
row.cell [0] = user.UserID.ToString();
row.cell [1] = user.UserName;
row.cell [2] = user.FirstName;
row.cell [3] = user.MiddleName;
row.cell [4] = user.LastName;
row.cell [5] = user.EmailID;
rows.Add(行);
}
result.rows = rows.ToArray();
result.page = PageIndex的;
result.total =总记录/ numberOfRows;
result.records =总记录;
返回新的JavaScriptSerializer()序列化(结果)。
} 私人收藏<使用者> GetUsers(字符串numberOfRows,字符串的PageIndex,串sortColumnName,串sortOrderBy,OUT INT总记录)
{
收藏<使用者>用户=新的集合<使用者>();
字符串的connectionString =; 使用(SqlConnection的连接=新的SqlConnection(的connectionString))
{
使用(的SqlCommand命令=新的SqlCommand())
{
command.Connection =连接;
command.CommandText =选择向tblUsers *;
command.CommandType = CommandType.Text; // StoredProcedure的; 的SqlParameter paramPageIndex =新的SqlParameter(@ PageIndex的SqlDbType.Int);
paramPageIndex.Value = Convert.ToInt32(PageIndex的);
command.Parameters.Add(paramPageIndex); 的SqlParameter paramColumnName =新的SqlParameter(@ SortColumnName,SqlDbType.VarChar,50);
paramColumnName.Value = sortColumnName;
command.Parameters.Add(paramColumnName); 的SqlParameter paramSortorderBy =新的SqlParameter(@ SortOrderBy,SqlDbType.VarChar,4);
paramSortorderBy.Value = sortOrderBy;
command.Parameters.Add(paramSortorderBy); 的SqlParameter paramNumberOfRows =新的SqlParameter(@ NumberOfRows,SqlDbType.Int);
paramNumberOfRows.Value = Convert.ToInt32(numberOfRows);
command.Parameters.Add(paramNumberOfRows); 的SqlParameter paramTotalRecords =新的SqlParameter(@总记录,SqlDbType.Int);
总记录= 0;
paramTotalRecords.Value =总记录;
paramTotalRecords.Direction = ParameterDirection.Output;
command.Parameters.Add(paramTotalRecords);
connection.Open(); 使用(SqlDataReader的的DataReader = Command.ExecuteReader却())
{
用户用户;
而(dataReader.Read())
{
用户=新用户();
user.UserID =(INT)的DataReader [用户名];
user.UserName = Convert.ToString(DataReader的[用户名]);
user.FirstName = Convert.ToString(DataReader的[名字]);
user.MiddleName = Convert.ToString(DataReader的[中间名]);
user.LastName = Convert.ToString(DataReader的[姓氏]);
user.EmailID = Convert.ToString(DataReader的[EMAILID]);
users.Add(用户);
}
}
总记录=(INT)paramTotalRecords.Value;
} 回报用户;
} }
公共BOOL IsReusable
{
//要启用池,在这里返回true。
//这将保持在内存中处理。
获得{返回false; }
}
}
}
}
客户端
<%@页面语言=C#AutoEventWireup =真codeBehind =sample.aspx.cs继承=sample.WebForm1%GT;!< DOCTYPE HTML PUBLIC - // W3C // DTD XHTML 1.0过渡// ENhttp://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">< HTML的xmlns =http://www.w3.org/1999/xhtml>
<头=服务器>
<标题>< /标题>
&所述;! - jQuery的用户界面的主题,将由网格使用 - >
<链接rel =stylesheet属性类型=文/ CSS媒体=屏幕上的href =http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.11/themes/redmond/jquery-ui的.css/>
<! - 在jQuery UI的主题扩展的jqGrid需求 - >
<链接rel =stylesheet属性类型=文/ CSS媒体=屏幕上的href =主题/ ui.jqgrid.css/>
<! - jQuery的运行时缩小的 - >
<脚本SRC =http://ajax.microsoft.com/ajax/jquery/jquery-1.5.2.min.js类型=文/ JavaScript的>< / SCRIPT>
<! - 我们需要的本地化文件,英语在这种情况下 - >
<脚本SRC =JS / trirand /国际化/ grid.locale-en.js类型=文/ JavaScript的>< / SCRIPT>
<! - 在jqGrid的客户端JavaScript - >
<脚本SRC =JS / trirand / jquery.jqGrid.min.js类型=文/ JavaScript的>< / SCRIPT> <脚本类型=文/ JavaScript的>
$(函数(){
$(#UsersGrid)。jqGrid的({
网址:'jqGridHandler.ashx',
数据类型:JSON,
高度:250,
colNames:用户名,用户名,名字,中间名,姓氏,EMAILID'],
colModel:
{名称:'用户名',索引:用户名,宽度:100,排序:真正},
{名:用户名,宽度:100,排序:真正},
{名称:'名字',宽度:100,排序:真正},
{名称:'中间名',宽度:100,排序:真正},
{名称:'姓氏',宽度:100,排序:真正},
{名称:'EMAILID',宽度:150,排序:真正}
]
的rowNum:10,
rowList:[10,20,30],
呼叫器:#UsersGridPager',
sortname:用户名,
viewrecords:真实,
排序顺序:ASC,
标题:JSON示例
}); $(#UsersGrid)的jqGrid('navGrid','#UsersGridPager',{编辑:假的,加:假的,德尔:假})。
}); < / SCRIPT>
< /头>
<身体GT;
<% - <表ID =的HtmlForm=服务器> - %GT;
<表ID =UsersGrid的cellpadding =0CELLSPACING =0>< /表>
< DIV ID =UsersGridPager>< / DIV> <% - < /形式为GT; - %GT;
< /身体GT;
< / HTML>
什么是错的呢?不显示数据。
谢谢
更新
$(文件)。就绪(函数(){
$阿贾克斯({
输入:POST,
的contentType:应用/ JSON的;字符集= UTF-8,
网址:jqGridHandler.ashx
数据类型:JSON,
成功:函数(结果){
VAR JQResult = JSON.parse(结果); 冷= JQResult.colData;
科隆= JQResult.colNames;
VAR科尔姆= JQResult.colModel; 警报(result.colModel);
jQuery的(#UsersGrid)。jqGrid的(
{
jsonReader:{repeatitems:假电池:,ID:0},
网址:jqGridHandler.ashx
数据类型:JSON,
MTYPE:'POST', 数据:性寒,
ColNames:科隆,
ColModel:科尔姆,
高度:自动,
GridView控件:真实,
传呼机:#UsersGrid',
的rowNum:5,
rowList:[5,10,20,50],
viewrecords:真实,
loadComplete:功能(数据){
警报('完全加载');
},
loadError:功能(){
警报('错误');
}
});
},
错误:函数(X,E){
警报(x.readyState +''+ x.status + e.msg);
}
}); });
有关动态的更新vesion
使用系统;
使用System.Collections.Generic;
使用System.Collections.ObjectModel;
使用System.Data这;
使用System.Data.SqlClient的;
使用的System.Web;
使用System.Web.Script.Serialization;命名空间jqGridInWebForm {
///<总结>
///为jqGridHandler摘要说明
///< /总结>
公共结构JQGridResults {
公众诠释页;
公众诠释总量;
公众诠释记录;
公共JQGridRow []的行;
}
公共结构JQGridRow {
公众诠释身份证;
公共字符串[]细胞;
}
公共枚举GridType
{
GRID_TYPE_TEXT,
GRID_TYPE_DATE,
GRID_TYPE_INT,
GRID_TYPE_DOUBLE
} [Serializable接口]
公共类用户{
公众诠释用户名{搞定;组; }
公共字符串用户名{获得;组; }
公共字符串名字{获得;组; }
公共字符串中间名{获得;组; }
公共字符串名字{获得;组; }
公共字符串EMAILID {搞定;组; }
公共字符串电话{搞定;组; } } 公共类clsGridData
{
公开名单<串GT; _Columns =新的List<串GT;();
公开名单<字符串[]> _Cells =新的List<字符串[]>(); 公共无效InitFields(字符串P_SQL,串P_TYPE)
{
INT _count;
字符串的connectionString =; // P_SQL
使用(SqlConnection的连接=新的SqlConnection(的connectionString))
{
使用(的SqlCommand命令=新的SqlCommand())
{
command.Connection =连接;
command.CommandText =选择向tblUsers *;
command.CommandType = CommandType.Text; // StoredProcedure的;
connection.Open(); 使用(SqlDataReader的的DataReader = Command.ExecuteReader却())
{
串MyField的;
对于(_count = 0;&_count LT; dataReader.FieldCount; _count ++)
{
MyField的= dataReader.GetName(_count);
_Columns.Add(MyField的);
} 而(dataReader.Read())
{
字符串[] =了myCell新的字符串[dataReader.FieldCount]
对于(_count = 0;&_count LT; dataReader.FieldCount; _count ++)
{
了myCell [_count = Convert.ToString(DataReader的[_count]);
}
_Cells.Add(了myCell);
}
} }
} }
} ///<总结>
///为jqgridhandler摘要说明
///< /总结>
公共类jqGridHandler:IHttpHandler的
{ 公共无效的ProcessRequest(HttpContext的背景下){
HTT prequest请求= context.Request;
HTT presponse响应= context.Response;
字符串_search =请求[_搜索];
字符串numberOfRows =请求[行];
字符串的PageIndex =请求[页];
字符串sortColumnName =请求[SIDX];
字符串sortOrderBy =请求[SORD]; // INT总记录;
//列表<使用者>用户= GetUsers(numberOfRows,PageIndex的,sortColumnName,sortOrderBy,出总记录);
clsGridData i_grid_data =新clsGridData();
i_grid_data.InitFields(,);
字符串输出= BuildJQGridResults(i_grid_data,Convert.ToInt32(numberOfRows),Convert.ToInt32(的PageIndex));
//字符串输出= BuildJQGridResults(用户,Convert.ToInt32(numberOfRows),Convert.ToInt32(PageIndex的),Convert.ToInt32(总记录));
RESPONSE.WRITE(输出);
} 私人字符串BuildJQGridResults(clsGridData P_GRID_DATA,诠释numberOfRows,诠释的PageIndex)
{ JQGridResults结果=新JQGridResults();
清单< JQGridRow>行=新的List< JQGridRow>();
INT _count; 的foreach(字符串[]在P_GRID_DATA._Cells细胞)
{
JQGridRow行=新JQGridRow();
row.cell =新的字符串[Cells.GetUpperBound(0)];
//row.id = user.UserID;
为(_count = 0; _count&下; Cells.GetUpperBound(0); _count ++)
{
row.cell [_count] =细胞[_count]的ToString();
}
rows.Add(行);
} result.rows = rows.ToArray();
result.page = PageIndex的;
result.total =(P_GRID_DATA._Cells.Count + numberOfRows - 1)/ numberOfRows;
result.records = P_GRID_DATA._Cells.Count;
返回新的JavaScriptSerializer()序列化(结果)。
}
//私人字符串BuildJQGridResults(列表<使用者>的用户,INT numberOfRows,诠释的PageIndex,诠释总记录){ // JQGridResults结果=新JQGridResults();
//列表< JQGridRow>行=新的List< JQGridRow> ();
//的foreach(在用户使用的用户)
// {
// JQGridRow行=新JQGridRow();
// row.id = user.UserID;
// row.cell =新的字符串[6]; // row.cell [0] = user.UserID.ToString();
// row.cell [1] = user.UserName;
// row.cell [2] = user.FirstName;
// row.cell [3] = user.MiddleName;
// row.cell [4] = user.LastName;
// row.cell [5] = user.EmailID;
// row.cell [6] = user.Phone; // rows.Add(行);
//}
// result.rows = rows.ToArray();
// result.page = PageIndex的;
// result.total =(总记录+ numberOfRows - 1)/ numberOfRows;
// result.records =总记录;
//返回新的JavaScriptSerializer().Serialize(结果);
//}
私人列表<使用者> GetDummyUsers(字符串numberOfRows,字符串的PageIndex,串sortColumnName,串sortOrderBy,OUT INT总记录)
{
VAR数据=新的List<使用者>
{
新用户(){EMAILID [email protected],名字=约翰,姓氏=阿拉亚,用户ID = 1,用户名=埃弗雷姆}
};
总记录= data.Count;
返回的数据;
}
私人列表<使用者> GetUsers(字符串numberOfRows,字符串的PageIndex,串sortColumnName,串sortOrderBy,OUT INT总记录)
{
清单<使用者>用户=新的List<使用者> (); 字符串的connectionString =; 使用(SqlConnection的连接=新的SqlConnection(的connectionString))
{
使用(的SqlCommand命令=新的SqlCommand())
{
command.Connection =连接;
command.CommandText =选择向tblUsers *;
command.CommandType = CommandType.Text; // StoredProcedure的; //的SqlParameter paramPageIndex =新的SqlParameter(@PageIndex,SqlDbType.Int);
//paramPageIndex.Value = Convert.ToInt32(PageIndex的);
//command.Parameters.Add(paramPageIndex); //的SqlParameter paramColumnName =新的SqlParameter(@SortColumnName,SqlDbType.VarChar,50);
//paramColumnName.Value = sortColumnName;
//command.Parameters.Add(paramColumnName); //的SqlParameter paramSortorderBy =新的SqlParameter(@SortOrderBy,SqlDbType.VarChar,4);
//paramSortorderBy.Value = sortOrderBy;
//command.Parameters.Add(paramSortorderBy); //的SqlParameter paramNumberOfRows =新的SqlParameter(@NumberOfRows,SqlDbType.Int);
//paramNumberOfRows.Value = Convert.ToInt32(numberOfRows);
//command.Parameters.Add(paramNumberOfRows); //的SqlParameter paramTotalRecords =新的SqlParameter(@TotalRecords,SqlDbType.Int);
//总记录= 0;
//paramTotalRecords.Value =总记录;
//paramTotalRecords.Direction = ParameterDirection.Output;
//command.Parameters.Add(paramTotalRecords);
connection.Open(); 使用(SqlDataReader的的DataReader = Command.ExecuteReader却())
{
用户用户;
而(dataReader.Read())
{
用户=新用户();
user.UserID =(INT)的DataReader [用户名];
user.UserName = Convert.ToString(DataReader的[用户名]);
user.FirstName = Convert.ToString(DataReader的[名字]);
user.MiddleName = Convert.ToString(DataReader的[中间名]);
user.LastName = Convert.ToString(DataReader的[姓氏]);
user.EmailID = Convert.ToString(DataReader的[EMAILID]);
users.Add(用户);
}
}
//总记录=(INT)paramTotalRecords.Value;
}
总记录= 0;
回报用户;
} }
公共BOOL IsReusable {
//要启用池,在这里返回true。
//这将保持在内存中处理。
获得{返回false; }
}
}
}
解决方案
我已经修改源,目前记录显示很顺利,但唯一的问题是,搜索不工作,可以请你看看?我的codeS给出如下:
aspx页面:
<%@页面语言=C#AutoEventWireup =真codeFILE =JQGrid.aspx.cs继承=jqGrid的%>!< DOCTYPE HTML PUBLIC - // W3C // DTD XHTML 1.0过渡// ENhttp://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">< HTML的xmlns =http://www.w3.org/1999/xhtml>
<头ID =头像1=服务器>
<标题>< /标题>
<% - <链接rel =stylesheet属性HREF =http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/themes/ui-darkness/jquery-ui.css类型= 文/ CSS媒体=所有/> - %GT; <链接rel =stylesheet属性类型=文/ CSS媒体=屏幕上的href =http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/redmond/jquery-ui的.css/>
<链接HREF =jqScripts / CSS / ui.jqgrid.css的rel =stylesheet属性类型=文/ CSS/>
<脚本SRC =http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js类型=文/ JavaScript的>< / SCRIPT>
<脚本SRC =jqScripts / JS /国际化/ grid.locale-en.js类型=文/ JavaScript的>< / SCRIPT>
<脚本SRC =jqScripts / JS / jquery.jqGrid.min.js类型=文/ JavaScript的>< / SCRIPT> <脚本类型=文/ JavaScript的>
$(函数(){
$(#UsersGrid)。jqGrid的({
网址:'jqGridHandler.ashx',
数据类型:JSON,
高度:250,
colNames:客户ID,公司名称,联系人姓名,联系人头衔,地址,城市,邮政code','国家'],
colModel:
{名称:'CUSTOMERID',索引:客户ID,宽度:75,排序:真正},
{名:公司名称,宽度:100,排序:真正},
{名称:'联系人姓名',宽度:100,排序:真正},
{名称:'联系人头衔',宽度:100,排序:真正},
{名称:'地址',宽度:100,排序:真正},
{名称:'市',宽度:100,排序:真正},
{名称:'邮政code',宽度:100,排序:真正},
{名称:'国家',宽度:150,排序:真正}
]
的rowNum:10,
rowList:[10,20,30],
呼叫器:#UsersGridPager',
sortname:客户ID,
viewrecords:真实,
排序顺序:ASC,
标题:我的数据
}); $(#UsersGrid)的jqGrid('navGrid','#UsersGridPager',{编辑:假的,加:假的,德尔:假})。
}); < / SCRIPT>< /头>
<身体GT;
<表ID =的HtmlForm=服务器>
<表ID =UsersGrid的cellpadding =0CELLSPACING =0>
< DIV ID =UsersGridPager>
< / DIV>
< /表>
< /表及GT;
< /身体GT;
< / HTML>
和ASHX:
<%@ WebHandler LANGUAGE =C#类=jqGridHandler%GT;使用系统;
使用System.Collections.Generic;使用System.Collections.ObjectModel;使用System.Data这;使用System.Data.SqlClient的;使用的System.Web;使用System.Web.Script.Serialization;公共类jqGridHandler:IHttpHandler的
{ 公共无效的ProcessRequest(HttpContext的背景下)
{
HTT prequest请求= context.Request;
HTT presponse响应= context.Response; 字符串_search =请求[_搜索];
字符串numberOfRows =请求[行];
//串numberOfRows =10;
字符串的PageIndex =请求[页];
字符串sortColumnName =请求[SIDX];
字符串sortOrderBy =请求[SORD];
INT总记录;
//公共的DataTable GetDataTable(字符串SIDX,串SORD,诠释页,诠释的pageSize)
收藏<使用者>用户= GetUsers(numberOfRows,PageIndex的,sortColumnName,sortOrderBy,出条,当前_search);
字符串输出= BuildJQGridResults(用户,Convert.ToInt32(numberOfRows),Convert.ToInt32(PageIndex的),Convert.ToInt32(总记录));
RESPONSE.WRITE(输出);
} 私人字符串BuildJQGridResults(集合<使用者>的用户,INT numberOfRows,诠释的PageIndex,INT总记录)
{ JQGridResults结果=新JQGridResults();
清单< JQGridRow>行=新的List< JQGridRow>();
的foreach(在用户使用的用户)
{
JQGridRow行=新JQGridRow();
row.id = user.CustomerID;
row.cell =新的字符串[8];
row.cell [0] = user.CustomerID;
row.cell [1] = user.CompanyName;
row.cell [2] = user.ContactName;
row.cell [3] = user.ContactTitle;
row.cell [4] = user.Address;
row.cell [5] = user.City;
row.cell [6] = user.Postal code;
row.cell [7] = user.Country; rows.Add(行);
}
result.rows = rows.ToArray();
result.page = PageIndex的;
result.total =总记录/ numberOfRows;
result.records =总记录;
返回新的JavaScriptSerializer()序列化(结果)。
} 私人收藏<使用者> GetUsers(字符串numberOfRows,字符串的PageIndex,串sortColumnName,串sortOrderBy,OUT INT条,当前字符串_search)
{
收藏<使用者>用户=新的集合<使用者>();
字符串的connectionString =数据源= ritetechno \\\\ sqlex preSS;初始目录=罗斯文;集成安全性=真;
//<添加名称=构造的connectionString =数据源=阿卜杜勒思考;初始目录=罗斯文;集成安全性=真的providerName =System.Data.SqlClient的/> 使用(SqlConnection的连接=新的SqlConnection(的connectionString))
{
使用(的SqlCommand命令=新的SqlCommand())
{
INT其行= Convert.ToInt32(numberOfRows)*(Convert.ToInt32(的PageIndex));
INT excluderows = Convert.ToInt32(numberOfRows)*((Convert.ToInt32(的PageIndex)-1));
command.Connection =连接;
command.CommandText =SELECT TOP+其行+客户ID,公司名称,联系人姓名,联系人头衔,地址,城市,邮政code国,来自客户的客户ID WHERE NOT IN(SELECT TOP+ excluderows +客户ID客户) ;
command.CommandType = CommandType.Text;
connection.Open(); 使用(SqlDataReader的的DataReader = Command.ExecuteReader却())
{
用户用户;
而(dataReader.Read())
{
用户=新用户();
user.CustomerID = Convert.ToString(DataReader的[客户ID]);
user.CompanyName = Convert.ToString(DataReader的[公司名称]);
user.ContactName = Convert.ToString(DataReader的[联系人姓名]);
user.ContactTitle = Convert.ToString(DataReader的[联系人头衔]);
user.Address = Convert.ToString(DataReader的[地址]);
user.City = Convert.ToString(DataReader的[市]);
user.Postal code = Convert.ToString(DataReader的[邮政code]);
user.Country = Convert.ToString(DataReader的[国家]);
users.Add(用户);
}
}
字符串cmdTotRec =SELECT COUNT(*)FROM客户;
的SqlCommand chkTotRec =新的SqlCommand(cmdTotRec,连接);
总记录= Convert.ToInt32(chkTotRec.ExecuteScalar()的ToString());
connection.close()时;
} 回报用户;
} }
公共BOOL IsReusable
{
//要启用池,在这里返回true。
//这将保持在内存中处理。
获得{返回false; }
} 公共结构JQGridResults
{
公众诠释页;
公众诠释总量;
公众诠释记录;
公共JQGridRow []的行; }
公共结构JQGridRow
{
公共字符串ID;
公共字符串[]细胞;
} [Serializable接口]
公共类用户
{
公共字符串客户ID {搞定;组; }
公共字符串公司名称{搞定;组; }
公共字符串联系人姓名{搞定;组; }
公共字符串联系人头衔{搞定;组; }
公共字符串地址{搞定;组; }
公共字符串城{搞定;组; }
公共字符串邮政code {搞定;组; }
公共字符串国家{搞定;组; }
}
}
I have created both client and server side for JQgrid and ASP.net. The grid is displayed but with no data. I could not see the result. The grid displayed but no data.
Server sidecoding
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Script.Serialization;
namespace sample
{
public struct JQGridResults
{
public int page;
public int total;
public int records;
public JQGridRow[] rows;
}
public struct JQGridRow
{
public int id;
public string[] cell;
}
[Serializable]
public class User
{
public int UserID
{ get; set; }
public string UserName
{ get; set; }
public string FirstName
{ get; set; }
public string MiddleName
{ get; set; }
public string LastName
{ get; set; }
public string EmailID
{ get; set; }
/// <summary>
/// Summary description for jqgridhandler
/// </summary>
public class jqGridHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string _search = request["_search"];
string numberOfRows = request["rows"];
string pageIndex = request["page"];
string sortColumnName = request["sidx"];
string sortOrderBy = request["sord"];
int totalRecords;
Collection<User> users = GetUsers(numberOfRows, pageIndex, sortColumnName, sortOrderBy, out totalRecords);
string output = BuildJQGridResults(users, Convert.ToInt32(numberOfRows), Convert.ToInt32(pageIndex), Convert.ToInt32(totalRecords));
response.Write(output);
}
private string BuildJQGridResults(Collection<User> users, int numberOfRows, int pageIndex, int totalRecords)
{
JQGridResults result = new JQGridResults();
List<JQGridRow> rows = new List<JQGridRow>();
foreach (User user in users)
{
JQGridRow row = new JQGridRow();
row.id = user.UserID;
row.cell = new string[6];
row.cell[0] = user.UserID.ToString();
row.cell[1] = user.UserName;
row.cell[2] = user.FirstName;
row.cell[3] = user.MiddleName;
row.cell[4] = user.LastName;
row.cell[5] = user.EmailID;
rows.Add(row);
}
result.rows = rows.ToArray();
result.page = pageIndex;
result.total = totalRecords / numberOfRows;
result.records = totalRecords;
return new JavaScriptSerializer().Serialize(result);
}
private Collection<User> GetUsers(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy, out int totalRecords)
{
Collection<User> users = new Collection<User>();
string connectionString = "";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "select * from tblusers" ;
command.CommandType = CommandType.Text; // StoredProcedure;
SqlParameter paramPageIndex = new SqlParameter("@PageIndex", SqlDbType.Int);
paramPageIndex.Value = Convert.ToInt32(pageIndex);
command.Parameters.Add(paramPageIndex);
SqlParameter paramColumnName = new SqlParameter("@SortColumnName", SqlDbType.VarChar, 50);
paramColumnName.Value = sortColumnName;
command.Parameters.Add(paramColumnName);
SqlParameter paramSortorderBy = new SqlParameter("@SortOrderBy", SqlDbType.VarChar, 4);
paramSortorderBy.Value = sortOrderBy;
command.Parameters.Add(paramSortorderBy);
SqlParameter paramNumberOfRows = new SqlParameter("@NumberOfRows", SqlDbType.Int);
paramNumberOfRows.Value = Convert.ToInt32(numberOfRows);
command.Parameters.Add(paramNumberOfRows);
SqlParameter paramTotalRecords = new SqlParameter("@TotalRecords", SqlDbType.Int);
totalRecords = 0;
paramTotalRecords.Value = totalRecords;
paramTotalRecords.Direction = ParameterDirection.Output;
command.Parameters.Add(paramTotalRecords);
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
User user;
while (dataReader.Read())
{
user = new User();
user.UserID = (int)dataReader["UserID"];
user.UserName = Convert.ToString(dataReader["UserName"]);
user.FirstName = Convert.ToString(dataReader["FirstName"]);
user.MiddleName = Convert.ToString(dataReader["MiddleName"]);
user.LastName = Convert.ToString(dataReader["LastName"]);
user.EmailID = Convert.ToString(dataReader["EmailID"]);
users.Add(user);
}
}
totalRecords = (int)paramTotalRecords.Value;
}
return users;
}
}
public bool IsReusable
{
// To enable pooling, return true here.
// This keeps the handler in memory.
get { return false; }
}
}
}
}
Client side
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="sample.aspx.cs" Inherits="sample.WebForm1" %>
<!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>
<!-- The jQuery UI theme that will be used by the grid -->
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.11/themes/redmond/jquery-ui.css" />
<!-- The jQuery UI theme extension jqGrid needs -->
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />
<!-- jQuery runtime minified -->
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.2.min.js" type="text/javascript"></script>
<!-- The localization file we need, English in this case -->
<script src="js/trirand/i18n/grid.locale-en.js"type="text/javascript"></script>
<!-- The jqGrid client-side javascript -->
<script src="js/trirand/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#UsersGrid").jqGrid({
url: 'jqGridHandler.ashx',
datatype: 'json',
height: 250,
colNames: ['UserID', 'UserName', 'FirstName', 'MiddleName', 'LastName', 'EmailID'],
colModel: [
{ name: 'UserID', index: 'UserID', width: 100, sortable: true },
{ name: 'UserName', width: 100, sortable: true },
{ name: 'FirstName', width: 100, sortable: true },
{ name: 'MiddleName', width: 100, sortable: true },
{ name: 'LastName', width: 100, sortable: true },
{ name: 'EmailID', width: 150, sortable: true }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: '#UsersGridPager',
sortname: 'UserID',
viewrecords: true,
sortorder: 'asc',
caption: 'JSON Example'
});
$("#UsersGrid").jqGrid('navGrid', '#UsersGridPager', { edit: false, add: false, del: false });
});
</script>
</head>
<body>
<%--<form id="HtmlForm" runat="server">--%>
<table id="UsersGrid" cellpadding="0" cellspacing="0"></table>
<div id="UsersGridPager"></div>
<%-- </form>--%>
</body>
</html>
What is wrong with it? Data is not displayed.Thank you
Updated
$(document).ready(function () {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: "jqGridHandler.ashx",
datatype: 'json',
success: function (result) {
var JQResult = JSON.parse(result);
colD = JQResult.colData;
colN = JQResult.colNames;
var colM = JQResult.colModel;
alert(result.colModel);
jQuery("#UsersGrid").jqGrid(
{
jsonReader: { repeatitems: false, cell: "", id: "0" },
url: "jqGridHandler.ashx",
datatype: 'json',
mtype: 'POST',
data: colD,
ColNames: colN,
ColModel: ColM,
height: "auto",
gridview: true,
Pager: '#UsersGrid',
rowNum: 5,
rowList: [5, 10, 20, 50],
viewrecords: true,
loadComplete: function (data) {
alert('loaded completely');
},
loadError: function () {
alert('error');
}
});
},
error: function (x, e) {
alert(x.readyState + ' ' + x.status + e.msg);
}
});
});
Updated vesion for dynamic one
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Script.Serialization;
namespace jqGridInWebForm {
/// <summary>
/// Summary description for jqGridHandler
/// </summary>
public struct JQGridResults {
public int page;
public int total;
public int records;
public JQGridRow[] rows;
}
public struct JQGridRow {
public int id;
public string[] cell;
}
public enum GridType
{
GRID_TYPE_TEXT,
GRID_TYPE_DATE,
GRID_TYPE_INT,
GRID_TYPE_DOUBLE
}
[Serializable]
public class User {
public int UserID { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string EmailID { get; set; }
public string Phone { get; set; }
}
public class clsGridData
{
public List<string> _Columns = new List<string>();
public List<string[]> _Cells = new List<string[]>();
public void InitFields(string P_SQL, string P_TYPE)
{
int _count;
string connectionString = "";//P_SQL
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "select * from tblusers";
command.CommandType = CommandType.Text; // StoredProcedure;
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
string MyField;
for (_count = 0; _count < dataReader.FieldCount; _count++)
{
MyField = dataReader.GetName(_count);
_Columns.Add(MyField);
}
while (dataReader.Read())
{
string[] MyCell = new string[dataReader.FieldCount];
for (_count = 0; _count < dataReader.FieldCount; _count++)
{
MyCell[_count] = Convert.ToString(dataReader[_count]);
}
_Cells.Add(MyCell);
}
}
}
}
}
}
/// <summary>
/// Summary description for jqgridhandler
/// </summary>
public class jqGridHandler: IHttpHandler
{
public void ProcessRequest(HttpContext context) {
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string _search = request["_search"];
string numberOfRows = request["rows"];
string pageIndex = request["page"];
string sortColumnName = request["sidx"];
string sortOrderBy = request["sord"];
//int totalRecords;
//List<User> users = GetUsers(numberOfRows, pageIndex, sortColumnName, sortOrderBy, out totalRecords);
clsGridData i_grid_data = new clsGridData();
i_grid_data.InitFields("","");
string output = BuildJQGridResults(i_grid_data, Convert.ToInt32(numberOfRows), Convert.ToInt32(pageIndex));
//string output = BuildJQGridResults(users, Convert.ToInt32(numberOfRows), Convert.ToInt32(pageIndex), Convert.ToInt32(totalRecords));
response.Write (output);
}
private string BuildJQGridResults(clsGridData P_GRID_DATA, int numberOfRows, int pageIndex)
{
JQGridResults result = new JQGridResults();
List<JQGridRow> rows = new List<JQGridRow>();
int _count;
foreach (String[] Cells in P_GRID_DATA._Cells)
{
JQGridRow row = new JQGridRow();
row.cell = new string[Cells.GetUpperBound(0)];
//row.id = user.UserID;
for (_count = 0;_count< Cells.GetUpperBound(0); _count++)
{
row.cell[_count] = Cells[_count].ToString();
}
rows.Add(row);
}
result.rows = rows.ToArray();
result.page = pageIndex;
result.total = (P_GRID_DATA._Cells.Count + numberOfRows - 1) / numberOfRows;
result.records = P_GRID_DATA._Cells.Count;
return new JavaScriptSerializer().Serialize(result);
}
//private string BuildJQGridResults(List<User> users, int numberOfRows, int pageIndex, int totalRecords) {
// JQGridResults result = new JQGridResults ();
// List<JQGridRow> rows = new List<JQGridRow> ();
// foreach (User user in users)
// {
// JQGridRow row = new JQGridRow ();
// row.id = user.UserID;
// row.cell = new string[6];
// row.cell[0] = user.UserID.ToString ();
// row.cell[1] = user.UserName;
// row.cell[2] = user.FirstName;
// row.cell[3] = user.MiddleName;
// row.cell[4] = user.LastName;
// row.cell[5] = user.EmailID;
// row.cell[6] = user.Phone ;
// rows.Add (row);
// }
// result.rows = rows.ToArray ();
// result.page = pageIndex;
// result.total = (totalRecords + numberOfRows - 1) / numberOfRows;
// result.records = totalRecords;
// return new JavaScriptSerializer ().Serialize (result);
//}
private List<User> GetDummyUsers(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy, out int totalRecords)
{
var data = new List<User>
{
new User(){EmailID = "[email protected]", FirstName = "John", LastName = "Araya", UserID = 1, UserName = "Efrem"}
};
totalRecords = data.Count;
return data;
}
private List<User> GetUsers(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy, out int totalRecords)
{
List<User> users = new List<User> ();
string connectionString = "";
using (SqlConnection connection = new SqlConnection (connectionString))
{
using (SqlCommand command = new SqlCommand ())
{
command.Connection = connection;
command.CommandText = "select * from tblusers";
command.CommandType = CommandType.Text; // StoredProcedure;
//SqlParameter paramPageIndex = new SqlParameter ("@PageIndex", SqlDbType.Int);
//paramPageIndex.Value = Convert.ToInt32 (pageIndex);
//command.Parameters.Add (paramPageIndex);
//SqlParameter paramColumnName = new SqlParameter ("@SortColumnName", SqlDbType.VarChar, 50);
//paramColumnName.Value = sortColumnName;
//command.Parameters.Add (paramColumnName);
//SqlParameter paramSortorderBy = new SqlParameter ("@SortOrderBy", SqlDbType.VarChar, 4);
//paramSortorderBy.Value = sortOrderBy;
//command.Parameters.Add (paramSortorderBy);
//SqlParameter paramNumberOfRows = new SqlParameter ("@NumberOfRows", SqlDbType.Int);
//paramNumberOfRows.Value = Convert.ToInt32 (numberOfRows);
//command.Parameters.Add (paramNumberOfRows);
//SqlParameter paramTotalRecords = new SqlParameter ("@TotalRecords", SqlDbType.Int);
//totalRecords = 0;
//paramTotalRecords.Value = totalRecords;
//paramTotalRecords.Direction = ParameterDirection.Output;
//command.Parameters.Add (paramTotalRecords);
connection.Open ();
using (SqlDataReader dataReader = command.ExecuteReader ())
{
User user;
while (dataReader.Read ())
{
user = new User ();
user.UserID = (int)dataReader["UserID"];
user.UserName = Convert.ToString (dataReader["UserName"]);
user.FirstName = Convert.ToString (dataReader["FirstName"]);
user.MiddleName = Convert.ToString (dataReader["MiddleName"]);
user.LastName = Convert.ToString (dataReader["LastName"]);
user.EmailID = Convert.ToString (dataReader["EmailID"]);
users.Add (user);
}
}
//totalRecords = (int)paramTotalRecords.Value;
}
totalRecords = 0;
return users;
}
}
public bool IsReusable {
// To enable pooling, return true here.
// This keeps the handler in memory.
get { return false; }
}
}
}
解决方案
I have modified the source, now records are displayed very smoothly but the only problem is that the search is not working, can you please have a look? My Codes are given below:
The aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JQGrid.aspx.cs" Inherits="JQGrid" %>
<!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 id="Head1" runat="server">
<title></title>
<%--<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/themes/ui-darkness/jquery-ui.css" type="text/css" media="all" />--%>
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/redmond/jquery-ui.css" />
<link href="jqScripts/css/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script src="jqScripts/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="jqScripts/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#UsersGrid").jqGrid({
url: 'jqGridHandler.ashx',
datatype: 'json',
height: 250,
colNames: ['CustomerID', 'CompanyName', 'ContactName', 'ContactTitle', 'Address', 'City', 'PostalCode', 'Country'],
colModel: [
{ name: 'CustomerID', index: 'CustomerID', width: 75, sortable: true },
{ name: 'CompanyName', width: 100, sortable: true },
{ name: 'ContactName', width: 100, sortable: true },
{ name: 'ContactTitle', width: 100, sortable: true },
{ name: 'Address', width: 100, sortable: true },
{ name: 'City', width: 100, sortable: true },
{ name: 'PostalCode', width: 100, sortable: true },
{ name: 'Country', width: 150, sortable: true }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: '#UsersGridPager',
sortname: 'CustomerID',
viewrecords: true,
sortorder: 'asc',
caption: 'My Data'
});
$("#UsersGrid").jqGrid('navGrid', '#UsersGridPager', { edit: false, add: false, del: false });
});
</script>
</head>
<body>
<form id="HtmlForm" runat="server">
<table id="UsersGrid" cellpadding="0" cellspacing="0">
<div id="UsersGridPager">
</div>
</table>
</form>
</body>
</html>
and the ashx:
<%@ WebHandler Language="C#" Class="jqGridHandler" %>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Script.Serialization;
public class jqGridHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string _search = request["_search"];
string numberOfRows = request["rows"];
//string numberOfRows = "10";
string pageIndex= request["page"];
string sortColumnName= request["sidx"];
string sortOrderBy = request["sord"];
int totalRecords;
//public DataTable GetDataTable(string sidx, string sord, int page, int pageSize)
Collection<User> users = GetUsers(numberOfRows, pageIndex, sortColumnName, sortOrderBy, out totalRecords, _search);
string output = BuildJQGridResults(users, Convert.ToInt32(numberOfRows), Convert.ToInt32(pageIndex), Convert.ToInt32(totalRecords));
response.Write(output);
}
private string BuildJQGridResults(Collection<User> users,int numberOfRows, int pageIndex,int totalRecords)
{
JQGridResults result = new JQGridResults();
List<JQGridRow> rows = new List<JQGridRow>();
foreach (User user in users)
{
JQGridRow row = new JQGridRow();
row.id = user.CustomerID;
row.cell = new string[8];
row.cell[0] = user.CustomerID;
row.cell[1] = user.CompanyName;
row.cell[2] = user.ContactName;
row.cell[3] = user.ContactTitle;
row.cell[4] = user.Address;
row.cell[5] = user.City;
row.cell[6] = user.PostalCode;
row.cell[7] = user.Country;
rows.Add(row);
}
result.rows = rows.ToArray();
result.page = pageIndex;
result.total = totalRecords / numberOfRows;
result.records = totalRecords;
return new JavaScriptSerializer().Serialize(result);
}
private Collection<User> GetUsers(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy, out int totalRecords, string _search)
{
Collection<User> users = new Collection<User>();
string connectionString = "Data Source=ritetechno\\sqlexpress;Initial Catalog=Northwind;Integrated Security=True";
//<add name="constr" connectionString="Data Source=Abdul-THINK;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
int numRows=Convert.ToInt32(numberOfRows)*(Convert.ToInt32(pageIndex));
int excluderows=Convert.ToInt32(numberOfRows)*((Convert.ToInt32(pageIndex)-1));
command.Connection = connection;
command.CommandText = "SELECT TOP " + numRows + " CustomerID, CompanyName, ContactName, ContactTitle, Address, City, PostalCode, Country FROM Customers WHERE CustomerID NOT IN (SELECT TOP " + excluderows +" CustomerID FROM Customers)";
command.CommandType = CommandType.Text;
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
User user;
while (dataReader.Read())
{
user = new User();
user.CustomerID = Convert.ToString(dataReader["CustomerID"]);
user.CompanyName = Convert.ToString(dataReader["CompanyName"]);
user.ContactName = Convert.ToString(dataReader["ContactName"]);
user.ContactTitle = Convert.ToString(dataReader["ContactTitle"]);
user.Address = Convert.ToString(dataReader["Address"]);
user.City = Convert.ToString(dataReader["City"]);
user.PostalCode = Convert.ToString(dataReader["PostalCode"]);
user.Country = Convert.ToString(dataReader["Country"]);
users.Add(user);
}
}
string cmdTotRec = "SELECT COUNT(*) FROM Customers";
SqlCommand chkTotRec = new SqlCommand(cmdTotRec, connection);
totalRecords = Convert.ToInt32(chkTotRec.ExecuteScalar().ToString());
connection.Close();
}
return users;
}
}
public bool IsReusable
{
// To enable pooling, return true here.
// This keeps the handler in memory.
get { return false; }
}
public struct JQGridResults
{
public int page;
public int total;
public int records;
public JQGridRow[] rows;
}
public struct JQGridRow
{
public string id;
public string[] cell;
}
[Serializable]
public class User
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
}
这篇关于的jqGrid不显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!