Ext.grid.Panel综合示例
包括
1、添加数据
2、简单搜索
3、编辑数据
4、删除数据
5、Ext 布局
其中用到了comboBox的二级、三级联动和默认值的设定,以及datefield的使用和numberfield的使用,现将代码提供如下:
HTML页面代码
<pre name="code" class="html"><!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Ext.datagrid远程加载数据(添加、删除和修改)</title> <!--<link rel="Stylesheet" type="text/css" href="ext-4.0.7-gpl/resources/css/ext-all.css" />--> <!--引入icon样式--> <!--<script type="text/javascript" src="ext-4.0.7-gpl/ext-all.js"></script> <script type="text/javascript" src="ext-4.0.7-gpl/bootstrap.js"></script> <script type="text/javascript" src="ext-4.0.7-gpl/ext-all-debug.js"></script> <script type="text/javascript" src="ext-4.0.7-gpl/locale/ext-lang-zh_CN.js"></script> <script type="text/javascript" src="js/Ext.data.grid CRUD.js"></script>--> <link rel="stylesheet" type="text/css" href="ext-4.2.1/resources/css/ext-all-neptune.css" /> <link rel="Stylesheet" type="text/css" href="ext-4.0.7-gpl/resources/css/icon.css" /> <script type="text/javascript" src="ext-4.2.1/bootstrap.js"></script> <script type="text/javascript" src="ext-4.2.1/locale/ext-lang-zh_CN.js"></script> <script type="text/javascript" src="js/Ext4.2.1.data.grid.CRUD.js"></script> </head> <body> </body> </html>
///<reference path="/ext-4.0.7-gpl/ext/ext-all.js"/> ///<reference path="/ext-4.0.7-gpl/ext-all-debug.js"/> ///<reference path="/ext-4.0.7-gpl/ext-all-dev.js"/> ///<reference path="/ext-4.2.1/bootstrap.js/> Ext.onReady(function () { Ext.QuickTips.init(); Ext.Loader.setConfig({ enable: true }); Ext.ClassManager.setAlias("Ext.selection.CheckboxModel", "selection.checkboxmodel"); //注册复选框选择模式别名为selection.checkboxmodel Ext.form.Field.prototype.msgTarget = "side"; //提示的方式 //定义分页变量 var pageSize = 20; //定义数据模型 var myModel = Ext.define("news", { extend: "Ext.data.Model", fields: [{ name: "ID", type: "int" }, { name: "Title", type: "Title" }, { name: "Comment", type: "Comment" }, { name: "Addtime", type: "string" }, { name: "Upptime", type: "string" }, { name: "Author", type: "string" }, { name: "TradeName", type: "string" }, { name: "isScrool", type: "int" }, { name: "Count", type: "int" }, { name: "Image", type: "string" }, { name: "UserName", type: "string" }, { name: "AreaName", type: "string" }] }); //定义Ext.data.Store对象 var newsStore = Ext.create("Ext.data.Store", { //指定数据记录 model: "news", //设置分页大小 pageSize: pageSize, //使用Proxy指定加载数据 proxy: { type: "ajax", url: "/AjaxHandler/newsOperate.ashx?action=search", reader: { type: "json", root: "data", //获取数据总是 totalProperty: "totalCount" } }, autoLoad: true }); //定义newsType数据模型 Ext.define("NewsType", { extend: "Ext.data.Model", fields: [ { name: "TypeName", type: "string" }, { name: "ID", type: "int" } ] }); //定义NewsType数据存储 var newsTypeStore = Ext.create("Ext.data.Store", { autoLoad: true, model: "NewsType", proxy: { type: "ajax", url: "/AjaxHandler/newsTypeOpearte.ashx?type=newstype", reader: { type: "json", root: "data" } } }); //定义新闻二级分类(SecondNewsType)数据模型 Ext.define("SecondNewsType", { extend: "Ext.data.Model", fields: [ { name: "TradeName", type: "string" }, { name: "ID", type: "int" }, { name: "NewsTypeID", type: "int" } ] }); var newsSecondTypeStore = Ext.create("Ext.data.Store", { autoLoad: false, model: "SecondNewsType", proxy: { type: "ajax", url: "/AjaxHandler/newsTypeOpearte.ashx?type=secondnewstype", reader: { type: "json", root: "data" } } }); //定义省份、地市、区县数据模型 Ext.define("Area", { extend: "Ext.data.Model", fields: [ { name: "AreaID", type: "int" }, { name: "LevelID", type: "string" }, { name: "AreaName", type: "string" }, { name: "gps_W", type: "float" }, { name: "gps_L", type: "float" } ] }); var provinceStore = Ext.create("Ext.data.Store", { autoLoad: true, model: "Area", proxy: { type: "ajax", url: "/AjaxHandler/AreaOperate.ashx?action=province", reader: { type: "json", root: "data" } } }); //地市comboBox var cityStore = Ext.create("Ext.data.Store", { autoLoad: true, model: "Area", proxy: { type: "ajax", url: "/AjaxHandler/AreaOperate.ashx?action=city", reader: { type: "json", root: "data" } } }); //区县comboBox var regionStore = Ext.create("Ext.data.Store", { autoLoad: true, model: "Area", proxy: { type: "ajax", url: "/AjaxHandler/AreaOperate.ashx?action=region", reader: { type: "json", root: "data" } } }); //扩展Ext.toolbar.Paging中的刷新 //定义分页 var pagebar = Ext.create("Ext.toolbar.Paging", { store: newsStore, displayInfo: true, displayMsg: "显示{0}-{1}条,共计{2}条", emptyMsg: "没有数据" }); //定义Ext.grid.Panel组件 var grid = Ext.create("Ext.grid.Panel", { title: "Ext.grid.Panel使用Ajax方式加载远程数据", width: "100%", store: newsStore, columnLines: true, rowLines: true, selType: "checkboxmodel", //设置单元格选中模式为Ext.selection.CheckboxModel // simpleSelect: true, multiSelect: true, viewConfig: { forceFit: true, stripeRows: true //在表格中显示斑马线 }, //启用简单选择功能 renderTo: Ext.getBody(), iconCls: "icon-grid", tbar: [{ xtype: "button", frame: true, text: "添加", scale: "small", tooltip: "添加新闻", iconCls: "Add", handler: AddNewsFn }, { xtype: "button", frame: true, text: "搜索", scale: "small", tooltip: "搜索", iconCls: "Magnifier", handler: SearchNewsFn }, { xtype: "button", frame: true, text: "编辑", scale: "small", tooltip: "编辑", iconCls: "Applicationformedit", handler: EditNewsFn }, { xtype: "button", frame: true, text: "删除", scale: "small", tooltip: "删除", iconCls: "Applicationformdelete", handler: DeleteNewsFn }, { xtype: "button", frame: true, text: "查看", scale: "small", tooltip: "查看", iconCls: "Diskmultiple", handler: LookNewsFn }, { xtype: "button", frame: true, text: "刷新", scale: "small", tooltip: "刷新", iconCls: "Tablerefresh", handler: RefreshNewsFn }], //分页功能 bbar: pagebar, //定义grid包含的所有数据列 columns: [{ text: "编号", dataIndex: "ID", align: "center", width: 50 }, { text: "新闻标题", dataIndex: "Title", align: "center", width: 230, renderer: rendererTitle }, { text: "新闻内容", dataIndex: "Comment", align: "center", width: 600, renderer: rendererComment }, { text: "添加时间", dataIndex: "Addtime", align: "center", width: 140, renderer: Ext.util.Format.dateRenderer('Y-m-d H:i:s') }, { text: "修改时间", dataIndex: "Upptime", align: "center", width: 140, renderer: Ext.util.Format.dateRenderer('Y-m-d H:i:s') }, { text: "新闻来源", dataIndex: "Author", align: "center", width: 80 }, { text: "新闻分类", dataIndex: "TradeName", align: "center", width: 80 }, { text: "是否焦点", dataIndex: "isScrool", align: "center", width: 60, renderer: scroolRenderer }, { text: "阅读次数", dataIndex: "Count", align: "center", width: 60 }, { text: "新闻图片", dataIndex: "Image", align: "center", width: 60 }, { text: "用户名称", dataIndex: "UserName", align: "center", width: 60 }, { text: "所属区域", dataIndex: "AreaName", align: "center", width: 60 } ] }); //搜索 function SearchNewsFn() { var win = Ext.create("Ext.window.Window", { title: "简单搜索", layout: { type: "vbox", align: "left" }, modal: true, //开启遮罩功能 items: [{ xtype: "textfield", fieldLabel: "新闻标题", name: "Title", id: "Title" }, { xtype: "textfield", fieldLabel: "新闻内容", name: "Comment", id: "Comment" }, { xtype: "datefield", fieldLabel: "开始时间(From)", name: "Addtimestart", format: "Y-m-d", id: "Addtimestart" }, { xtype: "datefield", fieldLabel: "开始时间(End)", name: "Addtimeend", id: "Addtimeend" }], buttons: [{ xtype: "button", frame: true, text: "搜索", scale: "small", tooltip: "搜索", iconCls: "Magnifier", handler: function () { //以Ajax方式发送请求 Ext.Ajax.request({ url: "/AjaxHandler/newsOperate.ashx?action=search", params: { Title: Ext.htmlEncode(Ext.getCmp("Title").getValue()), Comment: Ext.htmlEncode(Ext.getCmp("Comment").getValue()), start: 0, limit: 20 }, success: function (data) { //加载Ext.grid.Panel var respText = Ext.decode(data.responseText); //隐藏当前的窗口对象 win.setVisible(false); //搜索后重新加载newsStore var title = Ext.getCmp("Title").getValue(); var comment = Ext.getCmp("Comment").getValue(); newsStore.on("beforeload", function (store, options) { Ext.apply(store.proxy.extraParams, { Title: title, Comment: comment }); }); newsStore.load({ url: "/AjaxHandler/newsOperate.ashx?action=search", params: { start: 0, limit: 20, Title: title, Comment: comment } }); } }) } }] }).show(); win.setPagePosition(200, 100); win.setSize(300, 200); } function rendererTitle(title) { if (title != "" && Ext.getCmp("Title") != null && Ext.getCmp("Title").getValue() != "") { title = title.replace(Ext.getCmp("Title").getValue(), "<font color=\"red\"><b>" + Ext.getCmp("Title").getValue() + "</b></font>"); } return title; } function rendererComment(comment) { comment = setContent(comment); if (comment != "" && comment.length > 0) { return comment.substring(0, 70) + "……"; } else { return comment; } return comment; } function scroolRenderer(isscrool) { var result; if (isscrool == 1) { result = "<font color=\"red\">是</font>"; } if (isscrool == 0) { result = "<font color=\"blue\">否</font>"; } return result; } function dateformatter(datetime) { if (datetime != null) { var date = new Date(datetime); return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(); } } function setContent(str) { str = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag str.value = str.replace(/[ | ]*\n/g, '\n'); //去除行尾空白 //str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行 return str; } //添加功能 function AddNewsFn() { var winAdd = Ext.create("Ext.window.Window", { title: "添加新闻", modal: true, //resizable: false, items: [{ autoHeight: true, layout: "column", border: false, items: [{ columnWidth: .50, xtype: "fieldset", layout: "form", border: false, style: "margin-left:2px;padding-left:5px", fieldDefaults: { labelWidth: 70, labelAlign: "left" }, items: [{ xtype: "textfield", fieldLabel: "新闻标题", name: "Title", id: "Title", width: 400, emptyText: "请输入新闻标题", allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "datefield", fieldLabel: "添加时间", name: "Addtime", format: "Y-m-d", id: "Addtime", width: 400, emptyText: "请点击右侧的按钮选择时间", allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "datefield", fieldLabel: "更新时间", name: "Upptime", id: "Upptime", format: "Y-m-d", width: 400, emptyText: "请点击右侧的按钮选择时间", allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "textfield", fieldLabel: "新闻来源", name: "Author", id: "Author", width: 400, emptyText: "请输入该新闻的来源", allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "radiogroup", fieldLabel: "是否热点", columns: 2, items: [{ boxLabel: "是", name: "isScrool", inputValue: "1" }, { boxLabel: "否", name: "isScrool", inputValue: "0", checked: true }] }, { xtype: "numberfield", fieldLabel: "阅读次数", name: "Count", id: "Count", width: 300, emptyText: "请输入新闻的阅读次数", maxValue: 1000, minValue: 1, allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! } ] }, { columnWidth: 0.50, xtype: "fieldset", layout: "form", border: false, style: "margin-left:5px;padding-left:5px", fieldDefaults: { labelWidth: 70, labelAlign: "left" }, items: [ { xtype: "combo", name: "TypeName", fieldLabel: "一级分类", displayField: "TypeName", valueField: "ID", forceSelection: true, //要求输入值必须在列表中存在 id: "typeName", queryMode: "local", width: 200, store: newsTypeStore, emptyText: "请选择一级分类", triggerAction: "all", selectOnFocus: true, listeners: { "select": function () { var getCombo = Ext.getCmp("typeName"); newsSecondTypeStore.load({ params: { newsTypeID: getCombo.getValue() } }); } }, allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "combo", name: "TypeID", fieldLabel: "二级分类", displayField: "TradeName", valueField: "ID", forceSelection: true, //要求输入值必须在列表中存在 id: "tradeName", queryMode: "local", emptyText: "请选择二级分类", width: 200, store: newsSecondTypeStore, defaultListConfig: { loadMask: false }, //如果不设置LoadMask,数据已经取出,但是总显示加载中……(郁闷ing) allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "combo", name: "AreaName", fieldLabel: "省份", displayField: "AreaName", valueField: "LevelID", forceSelection: true, //要求输入值必须在列表中存在 emptyText: "请选择省份", id: "province", queryMode: "local", store: provinceStore, listeners: { "select": function () { cityStore.load({ params: { levelID: Ext.getCmp("province").getValue() } }); } }, allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "combo", name: "AreaName", fieldLabel: "城市", displayField: "AreaName", valueField: "LevelID", forceSelection: true, //要求输入值必须在列表中存在 id: "city", emptyText: "请选择城市", queryMode: "local", triggerAction: "all", store: cityStore, defaultListConfig: { loadMask: false }, listeners: { "select": function () { regionStore.load({ params: { levelID: Ext.getCmp("city").getValue() } }); } }, allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "combo", name: "AreaName", fieldLabel: "区县", displayField: "AreaName", valueField: "LevelID", forceSelection: true, id: "region", emptyText: "请选择区县", queryMode: "local", triggerAction: "all", store: regionStore, defaultListConfig: { loadMask: false }, allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! listeners: { "select": function () { Ext.Ajax.request({ url: "/AjaxHandler/AreaOperate.ashx", params: { action: "read", levelID: Ext.getCmp("region").getValue() }, success: function (data) { //给隐藏的控件赋值 var data = eval("(" + data.responseText + ")"); Ext.getCmp("CityID").setValue(data[0].AreaID); } }); } } }, { xtype: "textfield", fieldLabel: "添加人", name: "UserID", id: "UserID", allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! } ] }] }, { xtype: "fieldset", title: "新闻内容", border: false, style: "margin-left:2px;padding-left:5px", layout: "form", width: 688, items: [ { xtype: "htmleditor", style: "margin-left:2px;padding-left:5px", name: "Comment", id: "Comment", height: 180, emptyText: "请输入新闻来源", allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! } ] }, ], buttonAlign: "center", buttons: [{ text: "确定", handler: function () { var form = winAdd.items.get(0).getForm(); if (form.isValid()) { //以Ajax方式发送请求 Ext.Ajax.request({ url: "/AjaxHandler/newsOperate.ashx", params: { data: Ext.JSON.encode(form.getValues()), action: "add" }, success: function (resp, opts) { var respText = Ext.JSON.decode(resp.responseText); if (respText.success) { Ext.MessageBox.alert("提示", "添加成功", function () { winAdd.close(); newsStore.load({ params: { start: 0, limit: pageSize } }); }); } else { Ext.MessageBox.alert("提示", "添加失败"); } } }); } } }, { text: "重置", handler: function () { winAdd.items.get(0).getForm().reset(); } }, { text: "取消", handler: function () { winAdd.close(); } }] }).show(); winAdd.setPagePosition(200, 100); winAdd.setSize(700, 450); } //编辑功能 function EditNewsFn() { var rows = grid.getSelectionModel().getSelection(); if (rows.length == 0) { Ext.Msg.alert("提示", "请选择一行"); } else { var winEdit = Ext.create("Ext.window.Window", { title: "编辑标题为:\"" + rows[0].get("Title") + "\"信息", modal: true, resizable: false, items: [{ xtype: "form", bodyPadding: 10, id: "editform", items: [{ xtype: "textfield", fieldLabel: "ID", name: "ID", id: "ID", width: 400, emptyText: "请输入ID", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! readOnly: true, value: rows[0].get("ID") //给文本框内容赋值 }, { xtype: "textfield", fieldLabel: "新闻标题", name: "Title", id: "Title", width: 400, emptyText: "请输入新闻标题", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: rows[0].get("Title") }, { xtype: "datefield", fieldLabel: "添加时间", name: "Addtime", format: "Y-m-d H:i:s", id: "Addtime", width: 400, emptyText: "请点击右侧的按钮选择时间", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: Ext.util.Format.date(rows[0].get("Addtime"), "Y-m-d H:i:s") //datefield类型赋值 }, { xtype: "datefield", fieldLabel: "更新时间", name: "Upptime", id: "Upptime", format: "Y-m-d H:i:s", width: 400, emptyText: "请点击右侧的按钮选择时间", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: Ext.util.Format.date(rows[0].get("Upptime"), "Y-m-d H:i:s") //datefield类型赋值 }, { xtype: "textfield", fieldLabel: "新闻来源", name: "Author", id: "Author", width: 400, emptyText: "请输入该新闻的来源", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: rows[0].get("Author") }, { xtype: "radiogroup", fieldLabel: "是否热点", id: "isScrool", columns: 1, items: [{ boxLabel: "是", name: "isScrool", inputValue: "1" }, { boxLabel: "否", name: "isScrool", inputValue: "0" }] }, { xtype: "numberfield", fieldLabel: "阅读次数", name: "Count", id: "Count", width: 300, emptyText: "请输入新闻的阅读次数", maxValue: 1000, minValue: 1, allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: rows[0].get("Count") }, { xtype: "textfield", fieldLabel: "添加人", name: "UserID", id: "UserID", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: rows[0].get("UserName") }, { xtype: "combo", name: "TypeName", fieldLabel: "一级分类", displayField: "TypeName", valueField: "ID", forceSelection: true, //要求输入值必须在列表中存在 id: "typeName", queryMode: "local", store: newsTypeStore, emptyText: "请选择一级分类", triggerAction: "all", selectOnFocus: true, allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "combo", name: "TypeID", fieldLabel: "二级分类", displayField: "TradeName", valueField: "ID", forceSelection: true, //要求输入值必须在列表中存在 id: "tradeName", queryMode: "local", emptyText: "请选择二级分类", store: newsSecondTypeStore, defaultListConfig: { loadMask: false }, //如果不设置LoadMask,数据已经取出,但是总显示加载中……(郁闷ing) allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "combo", name: "AreaName", fieldLabel: "省份", displayField: "AreaName", valueField: "LevelID", forceSelection: true, //要求输入值必须在列表中存在 emptyText: "请选择省份", id: "province", queryMode: "local", store: provinceStore, allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "combo", name: "AreaName", fieldLabel: "城市", displayField: "AreaName", valueField: "LevelID", forceSelection: true, //要求输入值必须在列表中存在 id: "city", emptyText: "请选择城市", queryMode: "local", triggerAction: "all", store: cityStore, defaultListConfig: { loadMask: false }, allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "combo", name: "AreaName", fieldLabel: "区县", displayField: "AreaName", valueField: "LevelID", forceSelection: true, id: "region", emptyText: "请选择区县", queryMode: "local", triggerAction: "all", store: regionStore, defaultListConfig: { loadMask: false }, allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "hiddenfield", name: "CityID", id: "CityID" }, { xtype: "htmleditor", fieldLabel: "新闻内容", name: "Comment", id: "Comment", height: 180, emptyText: "请输入新闻来源", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: rows[0].get("Comment") }], buttonAlign: "center", buttons: [{ text: "确定", handler: function () { var form = winEdit.items.get(0).getForm(); if (form.isValid()) { //以Ajax方式发送请求 Ext.Ajax.request({ url: "/AjaxHandler/newsOperate.ashx", params: { data: Ext.JSON.encode(form.getValues()), action: "edit" }, success: function (resp, opts) { var respText = Ext.JSON.decode(resp.responseText); if (respText.success) { Ext.MessageBox.alert("提示", "保存成功", function () { winEdit.close(); newsStore.load({ params: { start: 0, limit: pageSize } }); }); } else { Ext.MessageBox.alert("提示", "保存失败"); } } }); } } }, { text: "取消", handler: function () { winEdit.close(); } }] }] }).show(); //绑定radiogroup var radioGroupitems = Ext.getCmp("isScrool").items; for (var i = 0; i < radioGroupitems.items.length; i++) { if (radioGroupitems.items[i].inputValue == rows[0].get("isScrool").toString()) { //radioGroupitems.items[i].checked = true; //此种方式不行,必须用以下赋值的方式赋值 radioGroupitems.items[i].setValue(rows[0].get("isScrool").toString()); } } //绑定comboBox //获取市级的数据 Ext.Ajax.request({ url: "/AjaxHandler/AreaOperate.ashx", params: { action: "readLevel", AreaName: rows[0].get("AreaName") }, success: function (data) { var data = eval("(" + data.responseText + ")"); var sLevelID = data[0].LevelID.substring(0, 6); //加载、绑定区县级别comboBox regionStore.load({ params: { levelID: sLevelID } }); Ext.getCmp("region").setValue(data[0].LevelID); //以赋值的方式绑定comboBox //加载、绑定地市级别comboBox cityStore.load({ params: { levelID: sLevelID.substring(0, 3) } }); Ext.getCmp("city").setValue(sLevelID); //绑定省份 Ext.getCmp("province").setValue(sLevelID.substring(0, 3)); //添加省份comboBox select事件 Ext.getCmp("province").on("select", function () { cityStore.load({ params: { levelID: Ext.getCmp("province").getValue() } }); }); //添加市级comboBo select事件 Ext.getCmp("city").on("select", function () { regionStore.load({ params: { levelID: Ext.getCmp("city").getValue() } }); }); //给隐藏的控件赋值 //Ext.getCmp("CityID").setValue(Ext.getCmp("region").getValue()); Ext.getCmp("region").on("select", function () { Ext.Ajax.request({ url: "/AjaxHandler/AreaOperate.ashx", params: { action: "read", levelID: Ext.getCmp("region").getValue() }, success: function (data) { //给隐藏的控件赋值 var data = eval("(" + data.responseText + ")"); Ext.getCmp("CityID").setValue(data[0].AreaID); } }); }); } }); //绑定新闻分类comboBox //获取新闻一级分类comboBox Ext.Ajax.request({ url: "/AjaxHandler/newsTypeOpearte.ashx", params: { type: "read", tradeName: rows[0].get("TradeName") }, success: function (data) { var data = eval("(" + data.responseText + ")"); //加载新闻二级分类comboBox newsSecondTypeStore.load({ params: { newsTypeID: data[0].NewsTypeID } }); //绑定新闻二级分类comboBox Ext.getCmp("tradeName").setValue(data[0].ID); //绑定新闻一级分类comboBox Ext.getCmp("typeName").setValue(data[0].NewsTypeID); //新闻一级分类comboBox添加select事件 Ext.getCmp("typeName").on("select", function () { newsSecondTypeStore.load({ params: { newsTypeID: Ext.getCmp("typeName").getValue() } }); }); } }); winEdit.setPagePosition(200, 100); winEdit.setSize(700, 650); } } /*#region删除新闻*/ function DeleteNewsFn() { /*#region 格式化相关列 */ Ext.window.MessageBox.prototype.buttonText = { ok: "确定", cancel: "取消", yes: "是", no: "否" }; Ext.MessageBox = Ext.Msg = new Ext.window.MessageBox(); //endregion var rows = grid.getSelectionModel().getSelection(); if (rows.length == 0) { Ext.Msg.alert("确认", "请选择一行"); } else { Ext.MessageBox.confirm(" 确认", "确定要删除吗?", function (btn) { if (btn == "yes") { Ext.Ajax.request({ url: "/AjaxHandler/newsOperate.ashx", params: { data: rows[0].get("ID"), action: "del" }, success: function (resp, opts) { var respText = Ext.JSON.decode(resp.responseText); if (respText.success) { Ext.MessageBox.alert("提示", "删除成功", function () { newsStore.load({ params: { start: 0, limit: pageSize } }); }); } else { Ext.MessageBox.alert("提示", "删除失败"); } } }); } }) //以Ajax方式发送请求 } } //查看功能 function LookNewsFn() { var rows = grid.getSelectionModel().getSelection(); if (rows.length == 0) { Ext.Msg.alert("提示", "请选择一行"); } else { var winLook = Ext.create("Ext.window.Window", { title: "查看标题为:\"" + rows[0].get("Title") + "\"详细", modal: true, resizable: false, items: [{ xtype: "form", bodyPadding: 10, id: "editform", items: [{ xtype: "textfield", fieldLabel: "ID", name: "ID", id: "ID", width: 400, emptyText: "请输入ID", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! readOnly: true, value: rows[0].get("ID") //给文本框内容赋值 }, { xtype: "textfield", fieldLabel: "新闻标题", name: "Title", id: "Title", width: 400, readOnly: true, emptyText: "请输入新闻标题", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: rows[0].get("Title") }, { xtype: "datefield", fieldLabel: "添加时间", name: "Addtime", format: "Y-m-d H:i:s", id: "Addtime", readOnly: true, width: 400, emptyText: "请点击右侧的按钮选择时间", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: Ext.util.Format.date(rows[0].get("Addtime"), "Y-m-d H:i:s") //datefield类型赋值 }, { xtype: "datefield", fieldLabel: "更新时间", name: "Upptime", id: "Upptime", readOnly: true, format: "Y-m-d H:i:s", width: 400, emptyText: "请点击右侧的按钮选择时间", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: Ext.util.Format.date(rows[0].get("Upptime"), "Y-m-d H:i:s") //datefield类型赋值 }, { xtype: "textfield", fieldLabel: "新闻来源", name: "Author", id: "Author", readOnly: true, width: 400, emptyText: "请输入该新闻的来源", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: rows[0].get("Author") }, { xtype: "radiogroup", fieldLabel: "是否热点", id: "isScrool", readOnly: true, columns: 1, items: [{ boxLabel: "是", name: "isScrool", inputValue: "1" }, { boxLabel: "否", name: "isScrool", inputValue: "0" }] }, { xtype: "numberfield", fieldLabel: "阅读次数", name: "Count", id: "Count", readOnly: true, width: 300, emptyText: "请输入新闻的阅读次数", maxValue: 1000, minValue: 1, allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: rows[0].get("Count") }, { xtype: "textfield", fieldLabel: "添加人", name: "UserID", readOnly: true, id: "UserID", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: rows[0].get("UserName") }, { xtype: "combo", name: "TypeName", fieldLabel: "一级分类", displayField: "TypeName", valueField: "ID", forceSelection: true, //要求输入值必须在列表中存在 id: "typeName", queryMode: "local", readOnly: true, store: newsTypeStore, emptyText: "请选择一级分类", triggerAction: "all", selectOnFocus: true, allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "combo", name: "TypeID", fieldLabel: "二级分类", displayField: "TradeName", valueField: "ID", forceSelection: true, //要求输入值必须在列表中存在 id: "tradeName", queryMode: "local", readOnly: true, emptyText: "请选择二级分类", store: newsSecondTypeStore, defaultListConfig: { loadMask: false }, //如果不设置LoadMask,数据已经取出,但是总显示加载中……(郁闷ing) allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "combo", name: "AreaName", fieldLabel: "省份", readOnly: true, displayField: "AreaName", valueField: "LevelID", forceSelection: true, //要求输入值必须在列表中存在 emptyText: "请选择省份", id: "province", queryMode: "local", store: provinceStore, allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "combo", name: "AreaName", readOnly: true, fieldLabel: "城市", displayField: "AreaName", valueField: "LevelID", forceSelection: true, //要求输入值必须在列表中存在 id: "city", emptyText: "请选择城市", queryMode: "local", triggerAction: "all", store: cityStore, defaultListConfig: { loadMask: false }, allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "combo", name: "AreaName", fieldLabel: "区县", readOnly: true, displayField: "AreaName", valueField: "LevelID", forceSelection: true, id: "region", emptyText: "请选择区县", queryMode: "local", triggerAction: "all", store: regionStore, defaultListConfig: { loadMask: false }, allowBlank: false, //不允许为空 blankText: "不能为空" //错误提示信息,默认为This field is required! }, { xtype: "htmleditor", fieldLabel: "新闻内容", name: "Comment", id: "Comment", readOnly: true, height: 180, emptyText: "请输入新闻来源", allowBlank: false, //不允许为空 blankText: "不能为空", //错误提示信息,默认为This field is required! value: rows[0].get("Comment") }] }] }).show(); //绑定radiogroup var radioGroupitems = Ext.getCmp("isScrool").items; for (var i = 0; i < radioGroupitems.items.length; i++) { if (radioGroupitems.items[i].inputValue == rows[0].get("isScrool").toString()) { //radioGroupitems.items[i].checked = true; //此种方式不行,必须用以下赋值的方式赋值 radioGroupitems.items[i].setValue(rows[0].get("isScrool").toString()); } } //绑定comboBox //获取市级的数据 Ext.Ajax.request({ url: "/AjaxHandler/AreaOperate.ashx", params: { action: "readLevel", AreaName: rows[0].get("AreaName") }, success: function (data) { var data = eval("(" + data.responseText + ")"); var sLevelID = data[0].LevelID.substring(0, 6); //加载、绑定区县级别comboBox regionStore.load({ params: { levelID: sLevelID } }); Ext.getCmp("region").setValue(data[0].LevelID); //以赋值的方式绑定comboBox //加载、绑定地市级别comboBox cityStore.load({ params: { levelID: sLevelID.substring(0, 3) } }); Ext.getCmp("city").setValue(sLevelID); //绑定省份 Ext.getCmp("province").setValue(sLevelID.substring(0, 3)); } }); //绑定新闻分类comboBox //获取新闻一级分类comboBox Ext.Ajax.request({ url: "/AjaxHandler/newsTypeOpearte.ashx", params: { type: "read", tradeName: rows[0].get("TradeName") }, success: function (data) { var data = eval("(" + data.responseText + ")"); //加载新闻二级分类comboBox newsSecondTypeStore.load({ params: { newsTypeID: data[0].NewsTypeID } }); //绑定新闻二级分类comboBox Ext.getCmp("tradeName").setValue(data[0].ID); //绑定新闻一级分类comboBox Ext.getCmp("typeName").setValue(data[0].NewsTypeID); } }); winEwinLookdit.setPagePosition(200, 100); winLook.setSize(700, 650); } } //刷新(重新加载) function RefreshNewsFn() { newsStore.load({ url: "/AjaxHandler/newsOperate.ashx?action=search", params: { start: 0, limit: 20 } }); } })
newsTypeOpearte.ashx代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; namespace Ext.AjaxHandler { /// <summary> /// newsTypeOpearte 的摘要说明 /// </summary> public class newsTypeOpearte : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/json"; //context.Response.Write("Hello World"); string type = context.Request.Params["type"]; switch (type) { case "newstype": ReaderNewsType(context); break; case "secondnewstype": ReaderSecondNewsType(context); break; case "read": ReadTypeIDByName(context); break; default: ReaderNewsType(context); break; } } protected void ReadTypeIDByName(HttpContext context) { string result = string.Empty; string TradeName = context.Request.Params["tradeName"]; using (Entities db = new Entities()) { List<SecondNewsType> secondNewsTypeList = new List<SecondNewsType>(); var query = (from s in db.SecondNewsType where s.TradeName == TradeName select s).OrderByDescending(t => t.ID); foreach (var item in query) { secondNewsTypeList.Add(new SecondNewsType() { ID = item.ID, NewsTypeID = item.NewsTypeID, TradeName = item.TradeName }); result = JsonConvert.SerializeObject(secondNewsTypeList); } } context.Response.Write(result); } protected void ReaderNewsType(HttpContext context) { string result = string.Empty; using(Entities db=new Entities ()) { List<NewsType> newsTypeList = new List<NewsType>(); var query = db.NewsType.OrderByDescending(t => t.ID); foreach (var item in query) { newsTypeList.Add(new NewsType() { CityID = item.CityID, ID = item.ID, Orders = item.Orders, TypeName = item.TypeName, Url = item.Url }); result = "{\"data\":" + JsonConvert.SerializeObject(newsTypeList) + "}"; } } context.Response.Write(result); } protected void ReaderSecondNewsType(HttpContext context) { string result = string.Empty; int typeID = context.Request.Params["newsTypeID"] == null ? 0 : int.Parse(context.Request.Params["newsTypeID"]); using (Entities db = new Entities()) { List<SecondNewsType> secondNewsTypeList = new List<SecondNewsType>(); var query = (from s in db.SecondNewsType where s.NewsTypeID == typeID select s).OrderByDescending(t => t.ID); foreach (var item in query) { secondNewsTypeList.Add(new SecondNewsType() { ID = item.ID, NewsTypeID = item.NewsTypeID, TradeName = item.TradeName }); result = "{\"data\":" + JsonConvert.SerializeObject(secondNewsTypeList) + "}"; } } context.Response.Write(result); } public bool IsReusable { get { return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; namespace Ext.AjaxHandler { /// <summary> /// AreaOperate 的摘要说明 /// </summary> public class AreaOperate : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/json"; string action = context.Request.Params["action"]; switch(action) { case "province": ReadProvince(context); break; case "city": ReadCity(context); break; case "region": ReadRegion(context); break; case "read": ReaderAreaIDByLevelID(context); break; case "readLevel": ReadLevelIDByName(context); break; default: ReadProvince(context); break; } } protected void ReaderAreaIDByLevelID(HttpContext context) { string result = string.Empty; string levelID = context.Request.Params["levelID"]; using (Entities db = new Entities()) { List<Aera> areaLists = new List<Aera>(); var query = from a in db.Aera where a.LevelID == levelID select a; foreach (var item in query) { areaLists.Add(new Aera() { AreaID = item.AreaID, AreaName = item.AreaName, gps_L = item.gps_L, gps_W = item.gps_W, LevelID = item.LevelID }); } result = JsonConvert.SerializeObject(areaLists); } context.Response.Write(result); } protected void ReadProvince(HttpContext context) { string result = string.Empty; using (Entities db = new Entities()) { List<Aera> areaLists = new List<Aera>(); var query = from a in db.Aera where a.LevelID.Length == 3 select a; foreach (var item in query) { areaLists.Add(new Aera() { AreaID = item.AreaID, AreaName = item.AreaName, gps_L = item.gps_L, gps_W = item.gps_W, LevelID = item.LevelID }); } result = "{\"data\":" + JsonConvert.SerializeObject(areaLists) + " }"; } context.Response.Write(result); } protected void ReadCity(HttpContext context) { string levelID = context.Request.Params["levelID"]; string result = string.Empty; using (Entities db = new Entities()) { List<Aera> areaLists = new List<Aera>(); var query = from a in db.Aera where a.LevelID.Length == 6 && a.LevelID.StartsWith(levelID) select a; foreach (var item in query) { areaLists.Add(new Aera() { AreaID = item.AreaID, AreaName = item.AreaName, gps_L = item.gps_L, gps_W = item.gps_W, LevelID = item.LevelID }); } result = "{\"data\":" + JsonConvert.SerializeObject(areaLists) + " }"; } context.Response.Write(result); } protected void ReadRegion(HttpContext context) { string levelID = context.Request.Params["levelID"]; string result = string.Empty; using (Entities db = new Entities()) { List<Aera> areaLists = new List<Aera>(); var query = from a in db.Aera where a.LevelID.Length ==9 && a.LevelID.StartsWith(levelID.Trim()) select a; foreach (var item in query) { areaLists.Add(new Aera() { AreaID = item.AreaID, AreaName = item.AreaName, gps_L = item.gps_L, gps_W = item.gps_W, LevelID = item.LevelID }); } result = "{\"data\":" + JsonConvert.SerializeObject(areaLists) + " }"; } context.Response.Write(result); } protected void ReadLevelIDByName(HttpContext context) { string AreaName = context.Request.Params["AreaName"]; string result = string.Empty; using (Entities db = new Entities()) { List<Aera> areaLists = new List<Aera>(); var query = from a in db.Aera where a.AreaName==AreaName select a; foreach (var item in query) { areaLists.Add(new Aera() { AreaID = item.AreaID, AreaName = item.AreaName, gps_L = item.gps_L, gps_W = item.gps_W, LevelID = item.LevelID }); } result = JsonConvert.SerializeObject(areaLists); } context.Response.Write(result); } public bool IsReusable { get { return false; } } } }newsOperate.ashx代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; namespace Ext.AjaxHandler { public class NewsView { public int ID { get; set; } public string Title { get; set; } public string Comment { get; set; } public DateTime Addtime { get; set; } public DateTime Upptime { get; set; } public string Author { get; set; } public string TradeName { get; set; } public int isScrool { get; set; } public int Count { get; set; } public string UserName { get; set; } public string AreaName { get; set; } public int CityID { get; set; } } /// <summary> /// newsOperate 的摘要说明 /// </summary> public class newsOperate : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/json"; //context.Response.Write("Hello World"); string action = context.Request.Params["action"]; switch(action) { case "load": loadNews(context); break; case "search": SearchNews(context); break; case "add": AddNews(context); break; case "edit": EditNews(context); break; case "del": DeleteNews(context); break; default : loadNews(context); break; } } protected void loadNews(HttpContext context) { 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; var total = 0; using (Entities db = new Entities()) { total = (from n in db.News join s in db.SecondNewsType on n.TypeID equals s.ID join u in db.Users on n.UserID equals u.ID join a in db.Aera on n.CityID equals a.AreaID select new { ID = n.ID, Title = n.Title, Comment = n.Comment, Addtime = n.Addtime, Upptime = n.Upptime, Author = n.Author, TradeName = s.TradeName, isScrool = n.isScrool, Count = n.Count, Image = n.Image, UserName = u.UserName, AreaName = a.AreaName }).OrderByDescending(n => n.ID).Count(); if((pageNum-1)*limit<total) { var query = (from n in db.News join s in db.SecondNewsType on n.TypeID equals s.ID join u in db.Users on n.UserID equals u.ID join a in db.Aera on n.CityID equals a.AreaID select new { ID = n.ID, Title = n.Title, Comment = n.Comment, Addtime = n.Addtime, Upptime = n.Upptime, Author = n.Author, TradeName = s.TradeName, isScrool = n.isScrool, Count = n.Count, Image = n.Image, UserName = u.UserName, AreaName = a.AreaName, CityID = a.AreaID }).OrderByDescending(n => n.ID).Skip((pageNum - 1) * limit).Take(limit); List<NewsView> newsList = new List<NewsView>(); foreach (var item in query) { newsList.Add(new NewsView() { Addtime = item.Addtime, AreaName = item.AreaName, Author = item.Author, Comment = item.Comment, Count = item.Count, ID = item.ID, isScrool = item.isScrool, Title = item.Title, TradeName = item.TradeName, Upptime = item.Upptime, UserName = item.UserName, CityID = item.CityID }); } result = "{\"totalCount\":" + total + ",\"data\":" + JsonConvert.SerializeObject(newsList) + "}"; context.Response.Write(result); } } } protected void SearchNews(HttpContext context) { int start = Convert.ToInt32(context.Request.Params["start"]); //起始第一页 int limit = Convert.ToInt32(context.Request.Params["limit"]); //每页显示的记录数 int pageNum = context.Request.Params["page"] == null ? 1 : Convert.ToInt32(context.Request.Params["page"]); //当前页 string result = string.Empty; //获取查询参数 string title = context.Request.Params["Title"] == null ? " " : context.Request.Params["Title"]; string comment = context.Request.Params["Comment"] == null ? " " : context.Request.Params["Comment"]; var total = 0; using (Entities db = new Entities()) { total = (from n in db.News where n.Title.Contains(title) && n.Comment.Contains(comment) join s in db.SecondNewsType on n.TypeID equals s.ID join u in db.Users on n.UserID equals u.ID join a in db.Aera on n.CityID equals a.AreaID select new { ID = n.ID, Title = n.Title, Comment = n.Comment, Addtime = n.Addtime, Upptime = n.Upptime, Author = n.Author, TradeName = s.TradeName, isScrool = n.isScrool, Count = n.Count, Image = n.Image, UserName = u.UserName, AreaName = a.AreaName }).OrderByDescending(n => n.ID).Count(); if ((pageNum - 1) * limit < total) { var query = (from n in db.News where n.Title.Contains(title) && n.Comment.Contains(comment) join s in db.SecondNewsType on n.TypeID equals s.ID join u in db.Users on n.UserID equals u.ID join a in db.Aera on n.CityID equals a.AreaID select new { ID = n.ID, Title = n.Title, Comment = n.Comment, Addtime = n.Addtime, Upptime = n.Upptime, Author = n.Author, TradeName = s.TradeName, isScrool = n.isScrool, Count = n.Count, Image = n.Image, UserName = u.UserName, AreaName = a.AreaName }).OrderByDescending(n => n.ID).Skip((pageNum - 1) * limit).Take(limit); List<NewsView> newsList = new List<NewsView>(); foreach (var item in query) { newsList.Add(new NewsView() { Addtime = item.Addtime, AreaName = item.AreaName, Author = item.Author, Comment = item.Comment, Count = item.Count, ID = item.ID, isScrool = item.isScrool, Title = item.Title, TradeName = item.TradeName, Upptime = item.Upptime, UserName = item.UserName }); } result = "{\"totalCount\":" + total + ",\"data\":" + JsonConvert.SerializeObject(newsList) + "}"; context.Response.Write(result); } } } protected void AddNews(HttpContext context) { string data = HttpUtility.UrlDecode(context.Request["data"]); string result = string.Empty; News news = JsonConvert.DeserializeObject<News>(data); //string jsonData = JsonConvert.DeserializeObject(data).ToString(); using (Entities db = new Entities()) { News addnews = new News() { Addtime = news.Addtime, Author = news.Author, CityID = news.CityID, Comment = news.Comment, Count = news.Count, Image = news.Image, isScrool = news.isScrool, Title = news.Title, TypeID = news.TypeID, Upptime = news.Upptime, UserID = news.UserID }; db.News.Add(addnews); int temp = db.SaveChanges(); result = "{ \"success\":true,\"data\":" + temp + " }"; } context.Response.Write(result); } protected void EditNews(HttpContext context) { string data = HttpUtility.UrlDecode(context.Request["data"]); string result = string.Empty; News news = JsonConvert.DeserializeObject<News>(data); using (Entities db = new Entities()) { News editnews = db.News.FirstOrDefault(n => n.ID == news.ID); editnews.Image = news.Image; editnews.isScrool = news.isScrool; editnews.Title = news.Title; editnews.TypeID = news.TypeID; editnews.Upptime = news.Upptime; editnews.UserID = news.UserID; editnews.Count = news.Count; editnews.Comment = news.Comment; editnews.CityID = news.CityID; editnews.Author = news.Author; editnews.Addtime = news.Addtime; int temp = db.SaveChanges(); result = "{ \"success\":true,\"data\":" + temp + " }"; } context.Response.Write(result); } protected void DeleteNews(HttpContext context) { int ID =int.Parse(HttpUtility.UrlDecode(context.Request["data"])); string result = string.Empty; // News news = JsonConvert.DeserializeObject<News>(data); using (Entities db = new Entities()) { News delnews = db.News.FirstOrDefault(n => n.ID == ID); db.News.Remove(delnews); int temp = db.SaveChanges(); result = "{ \"success\":true,\"data\":" + temp + " }"; } context.Response.Write(result); } public bool IsReusable { get { return false; } } } }
页面效果如下:
1、grid.Panel加载
2、搜索效果
4、编辑页面,其中comboBox加载时候自动绑定
5、查看