视频图像处理系列索引 || Arcgis/Engine/Server开发索引 || Web Map Gis开发索引 || jquery表格组件 JQGrid索引
WPF MVVM模式开发实现简明教程索引 || ArcGIS Runtime WPF(.net C#)开发简明教程索引

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: "WebService/UserHandler.ashx",
caption: "用户管理", //"User Information Management"
autowidth: true
});
//enable search/filter toolbar
//jQuery(grid_selector).jqGrid('filterToolbar',{defaultSearch:true,stringResult:true})
//switch element when editing inline
function aceSwitch(cellvalue, options, cell) {
setTimeout(function () {
$(cell).find('input[type=checkbox]')
.wrap('<label class="inline" />')
.addClass('ace ace-switch ace-switch-5')
.after('<span class="lbl"></span>');
}, 0);
}
//enable datepicker
function pickDate(cellvalue, options, cell) {
setTimeout(function () {
$(cell).find('input[type=text]')
.datepicker({ format: 'yyyy-mm-dd', autoclose: true });
}, 0);
}
//navButtons
jQuery(grid_selector).jqGrid('navGrid', pager_selector,
{ //navbar options
edit: true,
editicon: 'ui-icon-pencil blue',
edittext: '编辑',
add: true,
addicon: 'ui-icon-circle-plus',
addtext: '新增',
del: true,
delicon: 'ui-icon-circle-close red',
deltext: '删除',
search: true,
searchicon: 'ui-icon-search orange',
searchtext: '查找',
refresh: true,
refreshicon: 'ui-icon-refresh green',
refreshtext: '刷新',
view: true,
viewicon: 'ui-icon-circle-zoomin grey',
viewtext: '查看',
},
{
//edit record form
closeAfterEdit: true,
recreateForm: true,
beforeShowForm: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialogtitlebar').
wrapInner('<div class="widget-header" />')
style_edit_form(form);
},
afterSubmit: function (response, postdata) {
if (response.responseText != "") {
$(this).jqGrid('setGridParam', { datatype: 'json'
}).trigger('reloadGrid');
alert(response.responseText);
return [true, response.responseText]
}
}
},
{
//new record form
closeAfterAdd: true,
recreateForm: true,
viewPagerButtons: false,
beforeShowForm: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialogtitlebar').
wrapInner('<div class="widget-header" />')
style_edit_form(form);
},
afterSubmit: function (response, postdata) {
if (response.responseText != "") {
$(this).jqGrid('setGridParam', { datatype: 'json'
}).trigger('reloadGrid');
alert(response.responseText);
return [true, response.responseText]
}
}
},
{ //DELETE
delData: {
delId: function () {
var sel_id = [];
sel_id = $(grid_selector).jqGrid('getGridParam',
'selarrrow');
var value = '';
for (var i = 0; i < sel_id.length; i++) {
value = value + ',' + $(grid_selector).jqGrid('getCell',
sel_id[i], 'UserId');
}
if (value.charAt(0) == ',') {
value = value.substr(1);
}
return value;
}
},
closeOnEscape: true,
closeAfterDelete: true,
reloadAfterSubmit: true,
closeOnEscape: true,
drag: true,
afterSubmit: function (response, postdata) {
if (response.responseText != "") {
alert(response.responseText);
return [true, response.responseText]
}
}
},
{
//search form
closeOnEscape: true,
closeAfterSearch: true,
reloadAfterSubmit: true,
recreateForm: true,
afterShowSearch: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialogtitle').
wrap('<div class="widget-header" />')
style_search_form(form);
},
afterRedraw: function () {
style_search_filters($(this));
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(grid_selector).trigger("reloadGrid", [{ current: true }]);
return [false, response.responseText]
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json'
}).trigger('reloadGrid')
return [true, response.responseText]
}
},
multipleSearch: true
},
{
//view record form
recreateForm: true,
beforeShowForm: function (e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialogtitle').
wrap('<div class="widget-header" />')
}
}
)
function style_edit_form(form) {
//enable datepicker on "sdate" field and switches for "stock" field
//form.find('input[name=sdate]').datepicker({ format: 'yyyy-mm-dd',
autoclose: true })
// .end().find('input[name=stock]')
// .addClass('ace ace-switch ace-switch-5').wrap('<label
class="inline" />').after('<span class="lbl"></span>');
//update buttons classes
var buttons = form.next().find('.EditButton .fm-button');
buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//uiicon,
s-icon
buttons.eq(0).addClass('btn-primary').prepend('<i class="iconok"></
i>');
buttons.eq(1).prepend('<i class="icon-remove"></i>')
buttons = form.next().find('.navButton a');
buttons.find('.ui-icon').remove();
buttons.eq(0).append('<i class="icon-chevron-left"></i>');
buttons.eq(1).append('<i class="icon-chevron-right"></i>');
}
function style_delete_form(form) {
var buttons = form.next().find('.EditButton .fm-button');
buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//uiicon,
s-icon
buttons.eq(0).addClass('btn-danger').prepend('<i class="icontrash"></
i>');
buttons.eq(1).prepend('<i class="icon-remove"></i>')
}
function style_search_filters(form) {
form.find('.delete-rule').val('X');
form.find('.add-rule').addClass('btn btn-xs btn-primary');
form.find('.add-group').addClass('btn btn-xs btn-success');
form.find('.delete-group').addClass('btn btn-xs btn-danger');
}
function style_search_form(form) {
var dialog = form.closest('.ui-jqdialog');
var buttons = dialog.find('.EditTable')
buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btninfo').
find('.ui-icon').attr('class', 'icon-retweet');
buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btninverse').
find('.ui-icon').attr('class', 'icon-comment-alt');
buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btnpurple').
find('.ui-icon').attr('class', 'icon-search');
}
function beforeDeleteCallback(e) {
var form = $(e[0]);
if (form.data('styled')) return false;
form.closest('.ui-jqdialog').find('.ui-jqdialogtitlebar').
wrapInner('<div class="widget-header" />')
style_delete_form(form);
form.data('styled', true);
}
function beforeEditCallback(e) {
var form = $(e[0]);
form.closest('.ui-jqdialog').find('.ui-jqdialogtitlebar').
wrapInner('<div class="widget-header" />')
style_edit_form(form);
}
//it causes some flicker when reloading or navigating grid
//it may be possible to have some custom formatter to do this as the grid
is being created to prevent this
//or go back to default browser checkbox styles for the grid
function styleCheckbox(table) {
/**
$(table).find('input:checkbox').addClass('ace')
.wrap('<label />')
.after('<span class="lbl align-top" />')
$('.ui-jqgrid-labels th[id*="_cb"]:first-child')
.find('input.cbox[type=checkbox]').addClass('ace')
.wrap('<label />').after('<span class="lbl align-top" />');
*/
}
//unlike navButtons icons, action icons in rows seem to be hard-coded
//you can change them like this in here if you want
function updateActionIcons(table) {
/**
var replacement =
{
'ui-icon-pencil' : 'icon-pencil blue',
'ui-icon-trash' : 'icon-trash red',
'ui-icon-disk' : 'icon-ok green',
'ui-icon-cancel' : 'icon-remove red'
};
$(table).find('.ui-pg-div span.ui-icon').each(function(){
var icon = $(this);
var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
if($class in replacement) icon.attr('class', 'ui-icon
'+replacement[$class]);
})
*/
}
//replace icons with FontAwesome icons like above
function updatePagerIcons(table) {
var replacement =
{
'ui-icon-seek-first': 'icon-double-angle-left bigger-140',
'ui-icon-seek-prev': 'icon-angle-left bigger-140',
'ui-icon-seek-next': 'icon-angle-right bigger-140',
'ui-icon-seek-end': 'icon-double-angle-right bigger-140'
};
$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .uiicon').
each(function () {
var icon = $(this);
var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
if ($class in replacement) icon.attr('class', 'ui-icon ' +
replacement[$class]);
})
}
function enableTooltips(table) {
$('.navtable .ui-pg-button').tooltip({ container: 'body' });
$(table).find('.ui-pg-div').tooltip({ container: 'body' });
}
//var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');
});
</script>
<body>
<form id="form1" runat="server">
<div>
<table id="grid-table"></table>
<div id="grid-pager"></div>
</div>
</form>
</body>
</html>

 

posted @ 2016-06-29 18:00  jhlong  阅读(2753)  评论(2编辑  收藏  举报
海龙的博客 jhlong@cnblogs 版权所有© 转载请注明链接.有用请推荐一下
代码全部经过本人测试,但不保证复制粘贴就正常运行,更不保证能解决你的问题,请结合前后代码及描述理解后修改和使用