大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。
在前面写了两,但不知道如何完成,对比刚刚开始学这个,他们摸着石头过河,一步步。在最后两天DataGridCRUD融合在一起。因此份额。我希望像我这样谁是刚刚开始学习一些帮助。
直接主题酒吧。
它是说数据表,我建立了一个非常easy的表Rex_Test
ID | 自增序号 |
tName | 姓名 |
tEmail | 邮箱 |
前台代码:
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %> <!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" href="jquery-easyui-1.3.6/themes/default/easyui.css" /> <link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.6/themes/icon.css" /> <link rel="stylesheet" type="text/css" href="demo.css" /> <script type="text/javascript" src="jquery-easyui-1.3.6/jquery.min.js"></script> <script type="text/javascript" src="jquery-easyui-1.3.6/jquery.easyui.min.js"></script> <script type="text/javascript"> function getQueryParams(queryParams) { var tkey = document.getElementById("tkey").value; //alert(tkey); //$("#quanxian").combobox("getValue"); queryParams.tkey = tkey; return queryParams; } //添加查询參数,又一次载入表格 function reloadgrid() { //查询參数直接加入在queryParams中 var queryParams = $('#tt').datagrid('options').queryParams; getQueryParams(queryParams); $('#tt').datagrid('options').queryParams = queryParams; $("#tt").datagrid('reload'); } function add() { //清空内容 $('#fm').form('clear'); $('#dlg').dialog('open').dialog('setTitle', '加入邮箱'); document.getElementById("test").value = "add"; } //改动 function editUser() { var row = $('#tt').datagrid('getSelected'); if (row == null) { $.messager.alert("提示", "请选择要改动的行!", "info"); } if (row) { //获取要改动的字段 $('#tName').val(row.tName); $('#tEmail').val(row.tEmail); $('#dlg').dialog('open').dialog('setTitle', '改动邮箱'); document.getElementById("test").value = "modify"; $('#fm').form('load', row); } } function removeUser() { var test = document.getElementById("test").value = "delete"; var row = $('#tt').datagrid('getSelected'); if (row == null) { $.messager.alert("提示", "请选择要删除的行!", "info"); } if (row) { $.messager.confirm('提示', '你确定要删除这条信息吗?', function (r) { if (r) { $('#fm').form('submit', { url: 'Handler5.ashx/ProcessRequest?
ID=' + row.ID + "&test=" + test, onSubmit: function () { //return $(this).form('validate'); }, success: function (result) { if (result.indexOf("T") == 0) { $('#dlg').dialog('close'); //$('#tt').datagrid('clearSelections'); //清空选中的行 $.messager.alert("提示", "恭喜您。信息删除成功!
", "info"); //alert('恭喜您,信息删除成功!') // close the dialog $('#tt').datagrid('reload'); //$('#fm').form('submit'); } else { $.messager.alert("提示", "删除失败,请又一次操作!", "info"); //alert('加入失败,请又一次操作!
') return; //$('#fm').form('submit'); } } }); } }) } } function saveUser() { var tName = document.getElementById("tName").value; var tEmail = document.getElementById("tEmail").value; //alert(tName + "<br/>" + tEmail); var test = document.getElementById("test").value; if (test == "add") { $('#fm').form('submit', { url: "Handler5.ashx?test=" + test + "&tName=" + tName + "&tEmail=" + tEmail, onSubmit: function () { return $(this).form('validate'); }, success: function (result) { //alert(result); if (result.indexOf("T") == 0) { $('#dlg').dialog('close'); $.messager.alert("提示", "恭喜您,信息加入成功", "info"); //alert('恭喜您,信息加入成功!
') // close the dialog $('#tt').datagrid('reload'); //$('#fm').form('submit'); } else { $.messager.alert("提示", "加入失败,请又一次操作!
", "info"); return; //alert('加入失败,请又一次操作!') } } }); } else { var row = $('#tt').datagrid('getSelected'); if (row) { //获取要改动的字段 var ID = row.ID; //alert(ID); } $('#fm').form('submit', { url: "Handler5.ashx?
test=" + test + "&ID=" + ID + "&tName=" + tName + "&tEmail=" + tEmail, onSubmit: function () { return $(this).form('validate'); }, success: function (result) { if (result.indexOf("T") == 0) { $('#dlg').dialog('close'); //$('#tt').datagrid('clearSelections'); //清空选中的行 $.messager.alert("提示", "恭喜您,信息改动成功", "info"); //alert('恭喜您,信息加入成功。') // close the dialog $('#tt').datagrid('reload'); //$('#fm').form('submit'); } else { $.messager.alert("提示", "改动失败。请又一次操作。", "info"); return; //alert('加入失败。请又一次操作。') } } }); } } </script></head><body> <form id="fm" method="post"> <div> <%--表格显示区--%> <table id="tt" title="设置" class="easyui-datagrid" style="width: auto; height: 660px;" idField="ID" pagination="true" data-options="iconCls:'icon-save',rownumbers:true,url:'Handler5.ashx/ProcessRequest',pageSize:20, pageList:[20,30,40,50],method:'post',toolbar:'#tb',striped:true" fitcolumns="true"> <%--striped="true"--%> <%-- 表格标题--%> <thead> <tr> <th data-options="field:'ID',checkbox:true"> </th> <th data-options="field:'tName',width:100"> 姓名 </th> <th data-options="field:'tEmail',width:320,align:'center'"> 邮箱 </th> </tr> </thead> <%--表格内容--%> </table> <%--功能区--%> <div id="tb" style="padding: 5px; height: auto"> <%-- 包含加入,改动、删除 --%> <div style="margin-bottom: 5px"> <a href="javascript:void(0)" onclick="add()" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true"></a> <a href="javascript:void(0)" onclick="editUser() " class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true"></a> <a href="javascript:void(0)" onclick="removeUser()" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true"></a> </div> <%-- 查找信息 --%> <div> 姓名: <input id="tkey" /> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'" onclick="reloadgrid()"> Search</a> </div> </div> <div id="dlg" class="easyui-dialog" style="width: 400px; height: auto; padding: 10px 20px" data-options="closed:true,buttons:'#dlg-buttons'"> <%--closed="true" buttons="#dlg-buttons"--%> <div class="ftitle"> 邮箱信息</div> <div class="fitem"> <label> 姓名:</label> <input id="tName" name="tName" class="easyui-validatebox" data-options="required:true" /> </div> <div class="fitem"> <label> 邮箱:</label> <input id="tEmail" name="tEmail" class="easyui-validatebox" data-options="required:true" /> <input name="Test" id="test" type="hidden" /> <input name="ID" id="ID" type="hidden" /> <input id="key" name="key" onkeydown="if(event.keyCode==13)reloadgrid()" type="hidden" /> </div> </div> <div id="dlg-buttons"> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="saveUser()"> 保存</a> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'" onclick="javascript:$('#dlg').dialog('close')">关闭</a> </div> </div> </form></body></html>
然后这里就是一般处理程序
Handler5.ashx
<%@ WebHandler Language="C#" Class="Handler5" %> using System; using System.Web; using System.Data; using System.Data.SqlClient; using System.IO; using System.Text; public class Handler5 : IHttpHandler { public void ProcessRequest(HttpContext context) { string command = context.Request.QueryString["test"];//前台传的标示值 if (command == "add") {//调用加入方法 Add(context); } else if (command == "modify") {//调用改动方法 Modify(context); } else if (command == "delete") { Delete(context); } else { Query(context); } //Query(context); } public bool IsReusable { get { return false; } } public void Add(HttpContext context) { context.Response.ContentType = "text/plain"; string xx = string.Empty; string tname = context.Request.QueryString["tName"]; string temail = context.Request.QueryString["tEmail"]; SqlHelp sqla = new SqlHelp(); string sqlString = "insert into Rex_Test(tName,tEmail) values('" + tname + "','" + temail + "')"; bool aa= sqla.ExecuteNonQuery(sqlString); sqla.SqlClose(); if (aa) { xx = "True"; } else { xx="False"; } context.Response.Write(xx); } public void Modify(HttpContext context) { context.Response.ContentType = "text/plain"; string yy = string.Empty; string id = context.Request.QueryString["ID"]; string tname = context.Request.QueryString["tName"]; string temail = context.Request.QueryString["tEmail"]; SqlHelp sqlb = new SqlHelp(); string sqlString = "update Rex_Test set tName='"+tname+"',tEmail='"+temail+"' where ID='"+id+"'"; bool bb= sqlb.ExecuteNonQuery(sqlString); sqlb.SqlClose(); if (bb) { yy = "True"; } else { yy = "False"; } context.Response.Write(yy); } public void Delete(HttpContext context) { context.Response.ContentType = "text/plain"; string zz = string.Empty; string id=context.Request.QueryString["ID"]; SqlHelp sqlc = new SqlHelp(); string strfacc = "delete from Rex_Test where ID='"+id+"'"; sqlc.ExecuteNonQuery(strfacc); sqlc.SqlClose(); context.Response.Write("True"); } /// <summary> /// 查询记录 /// </summary> /// <param name="context"></param> public void Query(HttpContext context) { context.Response.ContentType = "text/plain"; //=============================================================== string tkey; tkey = ""; //获取前台传来的值 if (null != context.Request.QueryString["tkey"]) {//获取前台传来的值 tkey = context.Request.QueryString["tkey"].ToString().Trim(); } //================================================================ //获取分页和排序信息:页大小,页码,排序方式。排序字段 int pageRows, page; pageRows = 10; page = 1; string order, sort, oderby; order = sort = oderby = ""; if (null != context.Request.QueryString["rows"]) { pageRows = int.Parse(context.Request.QueryString["rows"].ToString().Trim()); } if (null != context.Request.QueryString["page"]) { page = int.Parse(context.Request.QueryString["page"].ToString().Trim()); } if (null != context.Request.QueryString["sort"]) { order = context.Request.QueryString["sort"].ToString().Trim(); } if (null != context.Request.QueryString["order"]) { sort = context.Request.QueryString["order"].ToString().Trim(); } //=================================================================== //组合查询语句:条件+排序 StringBuilder strWhere = new StringBuilder(); if (tkey != "") { strWhere.AppendFormat("tName like '%{0}%' and ", tkey); } //删除多余的and int startindex = strWhere.ToString().LastIndexOf("and");//获取最后一个and的位置 if (startindex >= 0) { strWhere.Remove(startindex, 3);//删除多余的andkeyword } if (sort != "" && order != "") { //strWhere.AppendFormat(" order by {0} {1}", sort, order);//加入排序 oderby = order + " " + sort; } //DataSet ds = Bnotice.GetList(strWhere.ToString()); //调用不分页的getlist //调用分页的GetList方法 DataSet ds = GetListByPage(strWhere.ToString(), oderby, (page - 1) * pageRows + 1, page * pageRows); int count = GetRecordCount(strWhere.ToString());//获取条数 string strJson = ToJson.Dataset2Json(ds, count);//DataSet数据转化为Json数据 context.Response.Write(strJson);//返回给前台页面 context.Response.End(); } public int GetRecordCount(string strWhere) { SqlHelp sqlx = new SqlHelp(); StringBuilder strSql = new StringBuilder(); strSql.Append("select count(1) FROM Rex_Test"); if (strWhere.Trim() != "") { strSql.Append(" where " + strWhere); } int obj = sqlx.ReturnCount(strSql.ToString()); sqlx.SqlClose(); if (obj<=0) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// 分页获取数据列表 /// </summary> public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex) { SqlHelp sqly = new SqlHelp(); try { StringBuilder strSql = new StringBuilder(); strSql.Append("SELECT * FROM ( "); strSql.Append(" SELECT ROW_NUMBER() OVER ("); if (!string.IsNullOrEmpty(orderby.Trim())) { strSql.Append("order by T." + orderby); } else { strSql.Append("order by ID asc"); } strSql.Append(")AS Row, T.* from Rex_Test T "); if (!string.IsNullOrEmpty(strWhere.Trim())) { strSql.Append(" WHERE " + strWhere); } strSql.Append(" ) TT"); strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex); return sqly.GetDataSet(strSql.ToString()); } finally { sqly.SqlClose(); } } }
最有另一个Json转换类
ToJson.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.Data; using System.Data.SqlClient; using System.IO; /// <summary> ///ToJson 的摘要说明 /// </summary> public class ToJson { /// <summary> /// DataSet转换成Json格式 /// </summary> /// <paramname="ds">DataSet</param> ///<returns></returns> public static string Dataset2Json(DataSet ds, int total = -1) { StringBuilder json = new StringBuilder(); foreach (DataTable dt in ds.Tables) { //{"total":5,"rows":[ json.Append("{\"total\":"); if (total == -1) { json.Append(dt.Rows.Count); } else { json.Append(total); } json.Append(",\"rows\":["); json.Append(DataTable2Json(dt)); json.Append("]}"); } return json.ToString(); } /// <summary> /// dataTable转换成Json格式 /// </summary> /// <paramname="dt"></param> ///<returns></returns> public static string DataTable2Json(DataTable dt) { StringBuilder jsonBuilder = new StringBuilder(); for (int i = 0; i <dt.Rows.Count; i++) { jsonBuilder.Append("{"); for (int j = 0; j <dt.Columns.Count; j++) { jsonBuilder.Append("\""); jsonBuilder.Append(dt.Columns[j].ColumnName); jsonBuilder.Append("\":\""); jsonBuilder.Append(dt.Rows[i][j].ToString()); jsonBuilder.Append("\","); } if (dt.Columns.Count > 0) { jsonBuilder.Remove(jsonBuilder.Length - 1, 1); } jsonBuilder.Append("},"); } if (dt.Rows.Count > 0) { jsonBuilder.Remove(jsonBuilder.Length - 1, 1); } return jsonBuilder.ToString(); } }
通过以上几步,基本上能够实现DataGrid的增删改查,其他功能还在学习中。请多多不吝赐教。
哦,对了,我发现这个Jqurey EasyUI DataGrid的一些功能,比方刷新、分页这些在IE11下。不怎么兼容样。假设有知道解决方法的朋友,希望能够留言。给大家分享一下,谢了。
近期有点时间。又来研究了一下这个问题。最终找到了问题所在,原来是method:’get’这里须要改为method:’post’,
这样子改动后。每次操作完毕又一次绑定数据后,就会又一次刷新了。
它似乎还有意向啊。
版权声明:本文博主原创文章,博客,未经同意不得转载。
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/116819.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...