Web jquery表格组件 JQGrid 的使用 - 全部代码

Posted 海龙的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Web jquery表格组件 JQGrid 的使用 - 全部代码相关的知识,希望对你有一定的参考价值。

 

系列索引

Web jquery表格组件 JQGrid 的使用 - 从入门到精通 开篇及索引

Web jquery表格组件 JQGrid 的使用 - 4.JQGrid参数、ColModel API、事件及方法

Web jquery表格组件 JQGrid 的使用 - 5.Pager翻页、搜索、格式化、自定义按钮

Web jquery表格组件 JQGrid 的使用 - 6.准备工作 & Hello JQGrid

Web jquery表格组件 JQGrid 的使用 - 7.查询数据、编辑数据、删除数据

Web jquery表格组件 JQGrid 的使用 - 8.Pager、新增数据、查询、刷新、查看数据

Web jquery表格组件 JQGrid 的使用 - 全部代码

Web jquery表格组件 JQGrid 的使用 - 11.问题研究

 

JQGrid导出Excel文件

 

目录

9.http handler 里的全部代码  

10.前端的全部代码

 

 

9.http handler 里的全部代码  

public class UserHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//查找
if (context.Request.Params.Get("_search") == "true")
{
string sfilters = context.Request.Params.Get("filters");
context.Response.Write(GetJson(SearchUsersDT(sfilters)));
return;
}
NameValueCollection forms = context.Request.Form;
string strOperation = forms.Get("oper");
string strResponse = string.Empty;
if (strOperation == null)
{
//排序
if (context.Request.Params.Get("sidx") != null &&
!string.IsNullOrEmpty(context.Request.Params.Get("sidx").ToString()) &&
context.Request.Params.Get("sord") != null &&
!string.IsNullOrEmpty(context.Request.Params.Get("sord").ToString()))
{
context.Response.Write(GetJson(GetUserDTSorted(context.Request.Params.Get("sidx").ToStr
ing(), context.Request.Params.Get("sord").ToString())));
return;
}
strResponse = GetJson(GetUserDT()); //load data
}
else if (strOperation == "del")
{
strResponse = DeleteUser(forms.Get("delId").ToString()) ? "删除成功!" :
"删除失败,请确认!";
}
else
{
AddEdit(forms, out strResponse);
}
context.Response.Write(strResponse);
}
private void AddEdit(NameValueCollection forms, out string strResponse)
{
string strOperation = forms.Get("oper");
string strEmpId = string.Empty;
User user = new User();
user.UserCode = forms.Get("UserCode").ToString();
user.Password = forms.Get("Password").ToString();
string sTmp = string.Empty;
if (strOperation == "add")
{
if (CheckUserExist(user.UserCode, ""))
{
sTmp = "用户名重复,请确认!";
}
else
{
sTmp = AddUser(user) ? "用户添加成功!" : "用户添加失败,请确认!";
}
}
else if (strOperation == "edit")
{
user.UserId = int.Parse(forms.Get("UserId").ToString());
if (CheckUserExist(user.UserCode, user.UserId.ToString()))
{
sTmp = "用户名重复,请确认!";
}
else
{
sTmp = UpdateUser(user) ? "用户更新成功!" : "用户更新失败,请确认!
";
}
}
strResponse = sTmp;
}
public bool IsReusable
{
get
{
return false;
}
}
private DataTable GetUserDT()
{
string cmdText = "SELECT UserId, UserCode, Password FROM T_User";
SQLHelper sqlhelper = new SQLHelper();
DataTable dt = sqlhelper.Selectinfo(cmdText);
return dt;
}
private string GetJson(DataTable dt)
{
javascriptSerializer serializer = new 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)
{
string s = dr[col].ToString(); //特殊情况
if (col.ColumnName == "IsAdmin")
{
s = s == "1" ? "" : "";
}

if (col.ColumnName == "HasWrite")
{
s = s == "1" ? "" : "";
}
row.Add(col.ColumnName.Trim(), s);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
/// <summary>
/// 根据jqgrid的查询操作符和字段拼接sql语句
/// </summary>
/// <param name="op">jqgrid的查询操作符</param>
/// <returns>sql wehere语句</returns>
/// <param name="field">查询字段名称</param>
private string GetSQLOperater(string op, string field)
{
string s = string.Empty;
switch (op)
{
case "eq": return field + " = @" + field;//等于
case "ne": return field + " <> @" + field;//不等于
case "bw": return field + " like @" + field + "\'%\'"; //开始于
case "bn": return field + " not like @" + field + "\'%\'"; //不开始于
case "ew": return field + " like \'%\' + @" + field; //结束于
case "en": return field + " not like \'%\' + @" + field; //不结束于
case "cn": return field + " like + \'%\' + " + field + "\'%\'"; //包含
case "nc": return field + " not like + \'%\' + @" + field + "\'%\'"; //不包
case "nu": return "(" + field + " = \'\' or is null)"; //空值
case "nn": return "(" + field + " <> \'\' or is not null)"; //非空值
case "in": return ""; //属于
case "ni": return ""; //不属于
default: return "";
}
}
private DataTable SearchUsersDT(string filters)
{
string jsonRes = string.Empty;
System.Runtime.Serialization.Json.DataContractJsonSerializer json = new
System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(GridSearch));
using (MemoryStream stream = new
MemoryStream(System.Text.Encoding.UTF8.GetBytes(filters)))
{
GridSearch gridSearch = (GridSearch)json.ReadObject(stream);
string groupOp = gridSearch.groupOp;
List<GridSearchRules> Rules = gridSearch.rules;
string sql = "select UserId, UserCode, Password FROM T_User";
mysqlParameter[] paras = new MySqlParameter[Rules.Count];
bool bFirst = true;
for (int i = 0; i < Rules.Count; i++)
{
GridSearchRules r = Rules[i];
string field = r.field;
string op = r.op;
string data = r.data;
sql = bFirst ? sql + " where " + GetSQLOperater(op, field) : sql +
groupOp + GetSQLOperater(op, field);
paras[i] = new MySqlParameter("@" + field, data);
}
SQLHelper sqlhelper = new SQLHelper();
DataTable dt = sqlhelper.Selectinfo(sql);
return dt;
}
}
private bool DeleteUser(string userId)
{
bool flag = true;
string[] idlist = userId.Split(\',\');
foreach (var sid in idlist)
{
string sql = "DELETE FROM T_User WHERE UserId=" + userId;
SQLHelper sqlhelper = new SQLHelper();
flag = sqlhelper.AddDelUpdate(sql) > 0;
}
return flag;
}
private bool AddUser(User objuser)
{
bool flag = false;
string cmdText = "INSERT INTO T_User (UserCode,Password) VALUES (\'" +
objuser.UserCode + "\',\'" + objuser.Password + "\')";
try
{
SQLHelper sqlhelper = new SQLHelper();
flag = sqlhelper.AddDelUpdate(cmdText) > 0;
}
catch (Exception ex)
{
throw ex;
}
return flag;
}
/// <summary>
/// 更新用户信息
/// </summary>
/// <param name="objuser"></param>
/// <returns>更新成功与否</returns>
private bool UpdateUser(User objuser)
{
string sql = "UPDATE T_User SET UserCode = \'" + objuser.UserCode +
"\',Password = \'" + objuser.Password + "\' WHERE UserId=" + objuser.UserId;
SQLHelper sqlhelper = new SQLHelper();
return sqlhelper.AddDelUpdate(sql) > 0;
}
private DataTable GetUserDTSorted(string field, string oper)
{
string cmdText = "SELECT UserId, UserCode, UserName, Password, RoleId,
CreateBy, CreateTime FROM T_User order by " + field + " " + oper;
SQLHelper sqlhelper = new SQLHelper();
DataTable dt = sqlhelper.Selectinfo(cmdText);
return dt;
}
private bool CheckUserExist(string UserCode, string UserId)
{
string sql = "select * from T_User where UserCode = \'" + UserCode + "\' and
UserId <> " + UserId;
SQLHelper sqlhelper = new SQLHelper();
DataTable dt = sqlhelper.Selectinfo(sql);
return dt == null || (dt != null && dt.Rows.Count == 1);
}
}

 

10.前端的全部代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="JQGrid/jquery-1.11.1.min.js"></script>
<link href="JQGrid/jquery-ui-1.11.1.custom/jquery-ui.css" rel="stylesheet" />
<script src="JQGrid/grid.locale-cn.js"></script>
<script src="JQGrid/jquery.jqGrid.js"></script>
<link href="JQGrid/ui.jqgrid.css" rel="stylesheet" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<script type="text/javascript">
jQuery(function ($) {
var grid_selector = "#grid-table";
var pager_selector = "#grid-pager";
jQuery(grid_selector).jqGrid({
url: "WebService/UserHandler.ashx",
datatype: "json",
height: 390,
colNames: [\' \', \'Id\', \'用户名\', \'密码\'],
colModel: [
{
name: \'myac\', index: \'\', width: 80, fixed: true, sortable:
false, resize: false,
formatter: \'actions\',
formatoptions: {
keys: true,
//editbutton: true,
editformbutton: true,
// extraparam: { oper: \'edit\' },
editOptions: { //编辑操作,这个很重要,实现编辑时传送参数
什么的。
reloadAfterSubmit: true,
//editData: {
// editkey: function () {
// var sel_id =
$(grid_selector).jqGrid(\'getGridParam\', \'selrow\');
// var value = $(grid_selector).jqGrid(\'getCell\',
sel_id, \'UserId\');
// return value;
// }
//},
closeAfterEdit: true,
afterSubmit: function (response, postdata) {
if (response.responseText != "") {
alert(response.responseText);
$(this).jqGrid(\'setGridParam\', { datatype:
\'json\' }).trigger(\'reloadGrid\');
return [true, response.responseText]
}
},
},
delOptions: { //删除操作,这个很重要,实现删除时传送参数什
么的。 这处网上没有例子的。
reloadAfterSubmit: true,
delData: {
delId: function () {
var sel_id =
$(grid_selector).jqGrid(\'getGridParam\', \'selrow\');
var value = $(grid_selector).jqGrid(\'getCell\',
sel_id, \'UserId\');
return value;
}
},
afterSubmit: function (response, postdata) {
if (response.responseText != "") {
alert(response.responseText);
$(this).jqGrid(\'setGridParam\', { datatype:
\'json\' }).trigger(\'reloadGrid\');
return [true, response.responseText]
}
}
},
}
},
{ name: \'UserId\', index: \'UserId\', width: 60, sorttype: "int",
editable: true, hidden: true },
{ name: \'UserCode\', index: \'UserCode\', width: 90, editable: true,
editrules: { required: true } },
{ name: \'Password\', index: \'Password\', type: "password", width: 120,
editable: true, editrules: { required: true } },
],
viewrecords: true,
rowNum: 10,
rowList: [10, 20, 30],
pager: pager_selector,
altRows: true,
multiselect: true,
multiboxonly: true,
loadonce: true, //设置这个才会分页
loadComplete: function (xhr) {
},
editurl: "<

以上是关于Web jquery表格组件 JQGrid 的使用 - 全部代码的主要内容,如果未能解决你的问题,请参考以下文章

Web jquery表格组件 JQGrid 的使用 - 6.准备工作 & Hello JQGrid

Web jquery表格组件 JQGrid 的使用 - 7.查询数据编辑数据删除数据

Web jquery表格组件 JQGrid 的使用 - 8.Pager新增数据查询刷新查看数据

Web jquery表格组件 JQGrid 的使用 - 5.Pager翻页搜索格式化自定义按钮

组件表格-jqGrid

组件表格-jqGrid