Ext.grid.Panel遠端載入資料分頁,提供新增刪除修改等操作
阿新 • • 發佈:2019-01-01
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;
}
}
}
}