Extjs4.1中grid更新数据传递到后台更新

现在项目中一直在有关extjs中的东西,一直想记录下做项目过程中的一些问题以及问题的解决,也算是一种笔记,方便自己以后查看,也能提供给遇到相同问题的人一种解决方式。

问题:Extjs中grid增加数据(更新,删除)数据后,如何更新到数据库?

解决方式很简单,只要能够把更新的记录以json的方式传递到后台,后台反序列化为更新的对象就可以了。关键是前台如何序列化,后台如何反序列化。忘了说了,我的后台是用的asp.net中的一般处理程序。因为是个例子,写的比较简单,先看看预览图片,

更新了姓名,点击保存,传递到后台

前台代码如下:

<!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>
    <title>更新gridpanel内容</title>
    <link href="http://www.cnblogs.com/Ext/resources/css/ext-all.css" rel="stylesheet" type="text/css" />
    <link href="http://www.cnblogs.com/Ext/resources/css/icon.css" rel="stylesheet" type="text/css" />
    <script src="http://www.cnblogs.com/Ext/ext-all.js" type="text/javascript"></script>
    <script src="http://www.cnblogs.com/Ext/locale/ext-lang-zh_CN.js" type="text/javascript"></script>
    <link href="http://www.cnblogs.com/Ext/resources/css/icon.css" rel="stylesheet" type="text/css" />

    <script src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="http://www.cnblogs.com/Scripts/jquery.json-2.4.js" type="text/javascript"></script>
    <script type="text/javascript">

        Ext.Loader.setConfig({
        enabled:true,
        });

        Ext.require([      
        'Ext.data.*',
        'Ext.grid.*',
        'Ext.selection.* ',
        'Ext.util.*',
        'Ext.Ajax.*'
        ]);

        Ext.onReady(function () {
            
            var celledit=Ext.create("Ext.grid.plugin.CellEditing",{
            clicksToEdit:1
            });

            Ext.define("UserModel",{
            extend:"Ext.data.Model",
            fields:[{
                           name:"id",type:"string" 
                     },{
                           name:"username",type:"string"
                     },{
                            name:"sex",type:"string"
                     },{
                          name:"age",type:"int"
                    },{
                         name:"birthday",type:"string"
                   },{
                        name:"classname",type:"string"
                    }]
            });

            var userstore=Ext.create("Ext.data.Store",{
            model:"UserModel",
            autoLoad:true,
            proxy:{
                        type:"ajax",
                        url:"/Data/griddata.js",
                        reader:{
                                       type:"json",
                                       root:"data",
                                       totalProperty:"totalcount"
                        }
                      }
            });
            userstore.load();
            var grid=Ext.create("Ext.grid.Panel",{
            store:userstore,
            columnLines:true,
            region:"center",
            title:"测试grid的增删改更新到后台",
            viewConfig:{stripeRows:true},
            selModel:Ext.create("Ext.selection.CheckboxModel"),
    
            columns:[Ext.create("Ext.grid.RowNumberer"),
            {
               text:"学号",
               dataIndex:"id",
               width:80,
               editor:{xtype:"textfield"}
            },{
              text:"姓名",
              dataIndex:"username",
              width:80,
              editor:{
              xtype:"textfield"
              }
            },{
              text:"行别",
              dataIndex:"sex",
              width:60,
              editor:{
              xtype:"combobox",
              store:[['0',''],['1','']]
              },
              renderer:function(val)
              {
                     return val=="0"?"":""
              }
            },{
              text:"年龄",
              dataIndex:"age",
              width:60,
              editor:{xtype:"numberfield"}
            },{
              text:"生日",
              dataIndex:"birthday",
              width:100,
              editor:{
                          xtype:"datefield",
                          format:"Y-m-d"
               },
             renderer: Ext.util.Format.dateRenderer('Y-m-d')
            },{
              text:"班级",
              dataIndex:"classname",
              width:60,
              editor:{
                          xtype:"combobox",
                          store:[['1','一班'],['2','二班']]
                          },
               renderer:function(val)
               {
                   return val=="1"?"一班":"二班"
               }
            }],
            plugins:celledit,
            tbar:Ext.create("Ext.toolbar.Toolbar",{
            items:[{
                           text:"添加",
                           iconCls:"Add",
                           handler:function(){
                             var item=Ext.create("UserModel",{
                             
                             });
                             var datastore=grid.getStore();
                             var index=datastore.getCount();
                             datastore.insert(index,item);
                             var sm=grid.getSelectionModel();
                             sm.select(index);
                           }
                      },{
                           text:"删除",
                           iconCls:"Delete",
                           handler:function(){
                     
                             var records = grid.getView().getSelectionModel().getSelection();
                                 if (records.length <= 0) {
                                    Ext.MessageBox.show({
                                        title: "错误",
                                        msg: "请选择您要删除的行",
                                        icon: Ext.MessageBox.ERROR,
                                        buttons: Ext.Msg.OKCANCEL
                                    });
                                    return;
                                }
                                else {
                                    Ext.Msg.confirm("提示", "您确定要删除吗", function (button, text) {
                                        if (button == "yes") {
                                            for (var i = 0; i < records.length; i++) {
                                                userstore.remove(records[i]);
                                            }
                                        }
                                    });
                                }
                           }
                     },{ 
                           text:"保存",
                           iconCls:"Save",
                           handler:function(){
                              var originalStore=grid.getStore();

                              var changeditems=originalStore.getModifiedRecords();
                              var array=new Array();

                              for(var i=0;i<changeditems.length;i++)
                              {
                                 array.push($.toJSON(changeditems[i].data));
                              }
                              //var newrcords=originalStore.getNewRecords();

                              //var deleterecords=originalStore.getRemovedRecords();
                              Ext.Ajax.request({
                              url:"/Handler/updategrid.ashx",
                              timeout:6000,
                              params:{
                              data:array
                              },
                              success:function(response)
                                  { 
                                       var text=response.responseText;
                                  }
                              });

                           }
                    }]
            })
            });

            Ext.create("Ext.container.Viewport",{
            layout:"border",
            border:false,
            items:[grid]
            });

        });
    </script>
</head>
<body>
</body>
</html>

主要是保存按钮中的事件,页面引用了jquery中一个json插件,可以把js对象转换为json字符串,这样后台也就可以接收到转换后的字符串了。

后台的代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace MyExtjsExample.Handler
{
    /// <summary>
    /// Summary description for updategrid
    /// </summary>
    public class updategrid : IHttpHandler
    {
        JavaScriptSerializer js = new JavaScriptSerializer();

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
         
            string strdata = context.Request["data"];
            var obj = js.Deserialize<UserInfo>(strdata);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

代码中使用了JavaScriptSerializer的反序列化方法,同样的,如果需要序列化对象传递到前台,也是可以的

类UserInfo代码如下,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

    public class UserInfo
    {
        public string id { get; set; }
        public string username { get; set; }
        public int age { get; set; }
        public string sex { get; set; }
        public string birthday { get; set; }
        public string classname { get; set; }
    }

前台代码中也有一些小的技巧和方法,日期字段在grid中的格式化,下拉框在grid中的使用,如何得到grid中新增加的记录,更改的记录,删除记录,都是可以以后学习借鉴的

posted @ 2013-02-28 11:50  myt  阅读(2136)  评论(0编辑  收藏  举报