Ext.grid.Panel远程加载NorthWind中Customers数据,并提供分页、添加、删除、修改和查看操作,界面如下图:
Ext.grid.Panel Ajax加载数据
添加界面
修改界面
查看界面
Extjs代码如下:
//Ext.grid.Panel动态加载和读取相关Customers信息 Ext.onReady(function () { Ext.QuickTips.init(); Ext.Loader.setConfig({ enable: true }); //定义数据模型 var myModel = Ext.define("Customers", { extend: "Ext.data.Model", fields: [ { name: "CustomerID", type: "string" }, { name: "CompanyName", type: "string" }, { name: "ContactName", type: "string" }, { name: "ContactTitle", type: "string" }, { name: "Address", type: "string" }, { name: "City", type: "string" }, { name: "Region", type: "string" }, { name: "PostalCode", type: "string" }, { name: "Country", type: "string" }, { name: "Phone", type: "string" }, { name: "Fax", type: "string" } ] }); //定义一个Ext.data.Store对象 var customerStore = Ext.create("Ext.data.Store", { //指定数据记录 model: "Customers", //设置分页大小 pageSize:15, //使用Proxy指定加载远程数据 proxy: { type: "ajax", url: "/AjaxHandler/getCustomersByUSA.ashx", reader: { type: "json", root: "data", //获取数据总数 totalProperty:"totalCount" } }, autoLoad: true }); //定义分页 var pagebar = Ext.create("Ext.toolbar.Paging", { store: customerStore, displayInfo: true, displayMsg: "显示{0}-{1}条,共计{2}条", emptyMsg: "没有数据" }); //定义Ext.grid.Panel组件 var grid = Ext.create("Ext.grid.Panel", { title: "Ext.grid.Panel使用Ajax方式加载远程数据", width: "75%", height: 450, store: customerStore, columnLines: true, //设置列线 rowLines:true, //设置行线 renderTo: Ext.getBody(), iconCls:"icon-grid", tbar:[{ xtype: "button", frame:true, text: "添加", scale: "small", tooltip: "添加Customers", cls: "x-btn-icon", //icon: "/ext-4.0.7-gpl/examples/button/images/add.gif", icon:"../icons/add.png", iconCls:"add", handler:AddCustomerFn }], //分页功能 bbar:pagebar, //定义grid包含的所有数据列 columns: [ { text: "CustomerID", dataIndex: "CustomerID",align:"center" }, { text: "CompanyName", dataIndex: "CompanyName",align:"center", editor: { xtype: "textfield", allowPattern: false } }, { text: "ContactName", dataIndex: "ContactName", align: "center", editor: { xtype: "textfield", allowPattern: false } }, { text: "ContactTitle", dataIndex: "ContactTitle", align: "center", editor: { xtype: "textfield", allowPattern: false } }, { text: "Address", dataIndex: "Address", align: "center", editor: { xtype: "textfield", allowPattern: false } }, { text: "City", dataIndex: "City", align: "center", editor: { xtype: "textfield", allowPattern: false } }, { text: "Region", dataIndex: "Region", align: "center", editor: { xtype: "textfield", allowPattern: false } }, { text: "PostalCode", dataIndex: "PostalCode", align: "center", editor: { xtype: "textfield", allowPattern: false } }, { text: "Country", dataIndex: "Country", align: "center", editor: { xtype: "textfield", allowPattern: false } }, { text: "Phone", dataIndex: "Phone", align: "center", editor: { xtype: "textfield", allowPattern: false } }, { text: "Fax", dataIndex: "Fax", align: "center", editor: { xtype: "textfield", allowPattern: false } }, { text: "操作", align:"center",html:"<font color=\"red\">操作</font>", xtype: "actioncolumn", items: [ { icon: "/images/edit.gif", tooltip: "编辑", handler: editFn, //指定单击”编辑“按钮的事件处理函数 align: "center", width:"100" }, { icon: "/images/del.gif", handler: deleteFn, //指定单击”删除“按钮的事件处理函数 tooltip: "删除", align: "center", width:"100" }, { icon: "/images/save.gif", handler: lookFn, //指定单击”查看“按钮的事件处理函数 tooltip: "查看", width:"100" } ] } ] }); //加载数据 customerStore.load({ params: { start: 0, limt: 15 } }); //定义编辑窗口 var editWin; //定义editFn编辑函数 function editFn(grid,rowIndex,colIndex) { //获取当前选中行的数据 var rec = grid.getStore().getAt(rowIndex); if (editWin) { editWin.setTitle("编辑《" + rec.get("CustomerID") + "》"); //给form组件赋值 var formFields = editWin.items.get(0).items; formFields.get(0).setValue(rec.get("CustomerID")); formFields.get(1).setValue(rec.get("CompanyName")); formFields.get(2).setValue(rec.get("ContactName")); formFields.get(3).setValue(rec.get("ContactTitle")); formFields.get(4).setValue(rec.get("Address")); formFields.get(5).setValue(rec.get("City")); formFields.get(6).setValue(rec.get("Region")); formFields.get(7).setValue(rec.get("PostalCode")); formFields.get(8).setValue(rec.get("Country")); formFields.get(9).setValue(rec.get("Phone")); formFields.get(10).setValue(rec.get("Fax")); } else { editWin = Ext.create("Ext.window.Window", { title: "编辑《" + rec.get("CustomerID") + "》", items: [ { // url: "/AjaxHandler/UpdateCustomers.ashx", xtype: "form", width: "100%", bodyPadding: 10, items: [ { xtype: "textfield", name: "CustomerID", readOnly: true, value: rec.get("CustomerID"), fieldLabel: "CustomerID", id:"CustomerID" }, { xtype: "textfield", name: "CompanyName", value: rec.get("CompanyName"), fieldLabel: "CompanyName", id:"CompanyName" }, { xtype: "textfield", name: "ContactName", value: rec.get("ContactName"), fieldLabel: "ContactName", id:"ContactName" }, { xtype: "textfield", name: "ContactTitle", value: rec.get("ContactTitle"), fieldLabel: "ContactTitle", id:"ContactTitle" }, { xtype: "textfield", name: "Address", value: rec.get("Address"), fieldLabel: "Address", id:"Address" }, { xtype: "textfield", name: "City", value: rec.get("City"), fieldLabel: "City", id:"City" }, { xtype: "textfield", name: "Region", value: rec.get("Region"), fieldLabel: "Region", id:"Region" }, { xtype: "textfield", name: "PostalCode", value: rec.get("PostalCode"), fieldLabel: "PostalCode", id:"PostalCode" }, { xtype: "textfield", name: "Country", value: rec.get("Country"), fieldLabel: "Country", id:"Country" }, { xtype: "textfield", name: "Phone", value: rec.get("Phone"), fieldLabel: "Phone", id:"Phone" }, { xtype: "textfield", name: "Fax", value: rec.get("Fax"), fieldLabel: "Fax", id:"Fax" } ] } ], listeners: { beforedestroy: function (cmp) { this.hide(); return false; } }, bbar: [ { xtype: "tbfill" }, { text: "确定", handler: function () { //获取表单,实际返回的是Ext.form.Basci对象 var form = editWin.items.get(0).getForm(); //获取表单项的内容,并形成JSON编码,以便后台读取 var strparas = Ext.encode(form.getValues()); //如果表单输入校验通过 if (form.isValid()) { //以Ajax方式提交表单 form.submit({ //修改成功的回调函数 url: "/AjaxHandler/UpdateCustomers.ashx?jsonstr="+strparas, clientValidation: true, //params: strparas, method:"GET", success: function (form, action) { //处理函数 Ext.Msg.alert("提示", "保存成功!"); editWin.close(); //关闭或隐藏当前的编辑窗口 //重新加载数据 customerStore.load({ params: { start: 0, limt: 15 } }); } }); } } }, { text: "取消", handler: function () { editWin.hide(); } }, { xtype: "tbfill" } ] }); } editWin.setVisible(true); } function getJson() { var CustomerID= Ext.getCmp("CustomerID").getValue(); var CompanyName= Ext.getCmp("CompanyName").getValue(); var ContactName= Ext.getCmp("ContactName").getValue(); var ContactTitle=Ext.getCmp("ContactTitle").getValue(); var Address=Ext.getCmp("Address").getValue(); var City= Ext.getCmp("City").getValue(); var Region=Ext.getCmp("Region").getValue(); var PostalCode=Ext.getCmp("PostalCode").getValue(); var Country=Ext.getCmp("Country").getValue(); var Phone = Ext.getCmp("Phone").getValue(); var Fax = Ext.getCmp("Fax").getValue(); var jsonObj = { CustomerID: CustomerID, CompanyName: CompanyName, ContactName: ContactName, ContactTitle: ContactTitle }; return jsonObj; } //定义deleteFn删除函数 function deleteFn(grid,rowIndex,colIndex) { if(Ext.MessageBox.confirm("友情提示","删除后,数据将不可恢复,请慎重!")) { var rec = grid.getStore().getAt(rowIndex); //Ajax方式发送请求 Ext.Ajax.request({ url: "/AjaxHandler/deleteCustomers.ashx", params: { //指定请求的参数 id:rec.get("CustomerID") }, //指定服务器响应完成的回调函数 success: function (response) { //提示删除成功,并重新加载grid组件数据 var respText = Ext.decode(response.responseText); Ext.Msg.alert("提示", "删除成功!,服务器返回为:" + respText); customerStore.load({ params: { start: 0, limt: 15} }); }, failure: function (response) { var respText = Ext.decode(response.responseText); Ext.Msg.alert("错误", respText.error); } }); } } //定义lookFn查看函数 function lookFn(grid,rowIndex,colIndex) { var rec = grid.getStore().getAt(rowIndex); //创建form表单显示查看的信息 var lookWin = Ext.create("Ext.window.Window", { title: "查看《" + rec.get("CustomerID") + "》详细信息", width: 300, height: 400, // frame: true, items: [ { xtype:"form", bodyPadding:10, items:[ { xtype: "textfield", fieldLabel: "CustomerID", readOnly: true, readOnlyCls: "x-form-readonly", value: rec.get("CustomerID") }, { xtype: "textfield", fieldLabel: "CompanyName", readOnly: true, readOnlyCls: "x-form-readonly", value: rec.get("CompanyName") }, { xtype: "textfield", fieldLabel: "ContactName", readOnly: true, readOnlyCls: "x-form-readonly", value: rec.get("ContactName") }, { xtype: "textfield", fieldLabel: "ContactTitle", readOnly: true, readOnlyCls: "x-form-readonly", value: rec.get("ContactTitle") }, { xtype: "textfield", fieldLabel: "Address", readOnly: true, readOnlyCls: "x-form-readonly", value: rec.get("Address") }, { xtype: "textfield", fieldLabel: "City", readOnly: true, readOnlyCls: "x-form-readonly", value: rec.get("City") }, { xtype: "textfield", fieldLabel: "Region", readOnly: true, readOnlyCls: "x-form-readonly", value: rec.get("Region") }, { xtype: "textfield", fieldLabel: "PostalCode", readOnly: true, readOnlyCls: "x-form-readonly", value: rec.get("PostalCode") }, { xtype: "textfield", fieldLabel: "Country", readOnly: true, readOnlyCls: "x-form-readonly", value: rec.get("Country") }, { xtype: "textfield", fieldLabel: "Phone", readOnly: true, readOnlyCls: "x-form-readonly", value: rec.get("Phone") }, { xtype: "textfield", fieldLabel: "Fax", readOnly: true, readOnlyCls: "x-form-readonly", value: rec.get("Fax") } ] } ] }); lookWin.setVisible(true); } // function AddCustomerFn() { //创建form表单显示查看的信息 var addkWin = Ext.create("Ext.window.Window", { title: "新建数据", width: 300, height: 400, resizable:false, items: [ { xtype: "form", id: "addform", width: "100%", bodyPadding: 10, items: [ { xtype: "textfield", fieldLabel: "CustomerID", allowBlank: false, name:"CustomerID" }, { xtype: "textfield", fieldLabel: "CompanyName", allowBlank: false, name:"CompanyName" }, { xtype: "textfield", fieldLabel: "ContactName", allowBlank: false, name:"ContactName" }, { xtype: "textfield", fieldLabel: "ContactTitle", allowBlank: false, name:"ContactTitle" }, { xtype: "textfield", fieldLabel: "Address", allowBlank: false, name:"Address" }, { xtype: "textfield", fieldLabel: "City", allowBlank: false, name:"City" }, { xtype: "textfield", fieldLabel: "Region", allowBlank: false, name:"Region" }, { xtype: "textfield", fieldLabel: "PostalCode", allowBlank: false, name:"PostalCode" }, { xtype: "textfield", fieldLabel: "Country", allowBlank: false, name:"Country" }, { xtype: "textfield", fieldLabel: "Phone", allowBlank: false, name:"Phone" }, { xtype: "textfield", fieldLabel: "Fax", allowBlank: false, name:"Fax" }, ] } ], //bbar: [ //{ xtype: "tbfill" }, //{ // text: "确定", align:"center", handler: function () // { // debugger; // var cc = addkWin.getComponent("addform"); // } //}, //{ // text: "取消", handler: function () // { // } //} //] buttons: [ { text: "确定", icon: "../icons/accept.png", scale: "small", handler: function () { //获取表单 //var form = addkWin.getComponent("addform");【此种方式不能条用getForm()方法,但是可以用getValues()方法,郁闷……】 var form = addkWin.items.get(0).getForm(); if (form.isValid()) { //Ajax方式发送请求 Ext.Ajax.request({ url: "/AjaxHandler/addCustomers.ashx", params: { jsonstr:Ext.encode(form.getValues()) }, success: function (response) { Ext.Msg.alert("提示", "新建成功!,服务器返回值为:" + response.responseText); //关闭当前的Window组件,返回grid组件界面,并重新加载grid addkWin.close(); //重新加载数据 customerStore.load({ params: { start: 0, limt: 15 } }); }, failure: function (response) { Ext.Msg.alert("提示", "新建失败!,服务器返回值为:" + response.responseText); //关闭当前的Window组件,返回grid组件界面,并重新加载grid addkWin.close(); //重新加载数据 customerStore.load({ params: { start: 0, limt: 15 } }); } }); } } }, { text: "取消", icon: "../icons/bullet_cross.png", scale: "small", handler: function () { //直接关闭当前 //关闭当前的Window组件,返回grid组件界面,并重新加载grid addkWin.close(); //重新加载数据 customerStore.load({ params: { start: 0, limt: 15 } }); } }, { text: "重置", icon: "../icons/arrow_redo.png", scale: "small", styel:"margin-rigth:250px;", handler: function () { //获取当前的form对象 var form = addkWin.items.get(0).getForm(); //重置表单中的全部字段 form.reset(); } } ] }); addkWin.setVisible(true); } });
<pre class="csharp" name="code">using System; using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; namespace Ext.AjaxHandler { /// <summary> /// addCustomers 的摘要说明 /// </summary> public class addCustomers : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; NorthwindEntities db = new NorthwindEntities(); string json = context.Request["jsonstr"]; Customers customer = JsonConvert.DeserializeObject<Customers>(json); Customers addCustomers = new Customers() { Address = customer.Address, City = customer.City, CompanyName = customer.CompanyName, ContactName = customer.ContactName, ContactTitle = customer.ContactTitle, Country = customer.Country, CustomerID = customer.CustomerID, Fax = customer.Fax, Phone = customer.Phone, PostalCode = customer.PostalCode, Region = customer.Region }; db.Customers.Add(addCustomers); int result=db.SaveChanges(); context.Response.Write("{success:true,data:" + result + "}"); } public bool IsReusable { get { return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using Newtonsoft.Json; namespace Ext.AjaxHandler { /// <summary> /// deleteCustomers 的摘要说明 /// </summary> public class deleteCustomers : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); string CustomerID = context.Request["id"]; NorthwindEntities db = new NorthwindEntities(); Customers customer= db.Customers.Single<Customers>(c => c.CustomerID == CustomerID); //由于Customers表和Orders\OrderDetails有关联[级联删除暂不操作] //var orders = from o in db.Orders // where o.CustomerID == CustomerID // select o; //foreach(var o in orders) //{ // var orderdetails = from od in db.Order_Details // where od.OrderID == o.OrderID // select od; //} db.Customers.Remove(customer); int result = db.SaveChanges(); context.Response.Write("{ success:true,result:" + result.ToString() + "}"); } public bool IsReusable { get { return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; using System.IO; using System.Text; namespace Ext.AjaxHandler { /// <summary> /// UpdateCustomers 的摘要说明 /// </summary> public class UpdateCustomers : IHttpHandler { //http://www.cnblogs.com/lipan/archive/2011/12/07/2269815.html public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string json = context.Request["jsonstr"]; int result = 0; //将获取的JSON字符串反序列化为Customers对象 Customers customer = JsonConvert.DeserializeObject<Customers>(json); using(NorthwindEntities db = new NorthwindEntities()) { Customers c = db.Customers.FirstOrDefault(cc => cc.CustomerID == customer.CustomerID); c.Address = customer.Address; c.City = customer.City; c.CompanyName = customer.CompanyName; c.ContactName = customer.ContactName; c.ContactTitle = customer.ContactTitle; c.Country = customer.Country; c.Fax = customer.Fax; c.Phone = customer.Phone; c.PostalCode = customer.PostalCode; c.Region = customer.Region; result= db.SaveChanges(); } context.Response.Write("{success:true,data:" + result + "}"); } public bool IsReusable { get { return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; using System.Data.SqlClient; using System.Data; namespace Ext.AjaxHandler { /// <summary> /// getCustomersByUSA 的摘要说明 /// </summary> public class getCustomersByUSA : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/json"; int start = Convert.ToInt32(context.Request.Params["start"]); //起始第一页 int limit = Convert.ToInt32(context.Request.Params["limit"]); //每页显示的记录数 int pageNum = Convert.ToInt32(context.Request.Params["page"].ToString()); //当前页 string result = string.Empty; #region 传统的AdoNet方式 //string Sql = "Select Top " + limit + " * From Customers Where (CustomerID NOT IN(Select Top " + start + " CustomerID From Customers Order By CustomerID)) Order By CustomerID"; //DataTable dt = SqlHelper.ExecuteDataSet(SqlHelper.con_string, "Customers", CommandType.Text, Sql, null).Tables[0]; //int totalCount = getTotal(); //result = "{\"totalCount\":" + totalCount + ",\"data\":" + JsonConvert.SerializeObject(dt) + "}"; //context.Response.Write(result); #endregion #region Linq方式 NorthwindEntities db = new NorthwindEntities(); var totalCount = db.Customers.OrderBy(c => c.CustomerID).Count(); if ((pageNum-1) * limit < totalCount) { var query = db.Customers.OrderBy(c => c.CustomerID).Skip((pageNum-1) * limit).Take(limit); List<Customers> customerList = new List<Customers>(); foreach (var item in query) { customerList.Add(new Customers() { Address = item.Address, City = item.City, Country = item.Country, CompanyName = item.CompanyName, ContactName = item.ContactName, ContactTitle = item.ContactTitle, CustomerID = item.CustomerID, Fax = item.Fax, Phone = item.Phone, PostalCode = item.PostalCode, Region = item.Region }); } result = "{\"totalCount\":" + totalCount + ",\"data\":" + JsonConvert.SerializeObject(customerList) + "}"; } context.Response.Write(result); #endregion } public int getTotal() { string Sql = "Select Count(*) As count From Customers"; DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.con_string, "Customers", CommandType.Text, Sql, null); int total = int.Parse(ds.Tables[0].Rows[0]["count"].ToString()); return total; } public bool IsReusable { get { return false; } } } }