• 《Ext JS高级程序设计》节选: 一个结合DataWrite和RowEditor的Grid示例(2)


     

    在定义中,需要监听 beforeedit 事件,其作用是判断当前编辑状态是增加新记录还是编辑原有记录,如果是增加新记录,则 cid 字段的输入框需要处于允许编辑状态。否则, cid 字段的输入框需要处于不允许编辑状态。因为当新增一个记录时, Sotre 记录集中的每个记录的关键字使用的是 id 的值,而不是 cid 的值,虽然在新增操作成功后,会根据服务器端返回的记录修改这个关键字,但是,当再次编辑该记录并修改其 cid 值时,并不会再更新记录集中该记录的关键字,因而当你第 3 次编辑该记录时,在服务器端将找不到该记录,从而引发错误。这就是使用两个 id 的弊端。因而,要在这里禁止在编辑原有记录时修改 cid 值。

    接着定义 cid 字段的 TextField ,代码如下:

            var ideditor=new Ext.form.TextField({

                               allowBlank: false,maskRe:/[0-9]/,regex:/^(/d{3})*$/,         regexText:" 请输入正确的编号 "

                       });

    定义中,参数 maskRe 限制了输入框只能输入数字。参数 regex 限制了输入的数字的个数必须为 3 的倍数,而参数 regexText 则是验证 regex 时输出的错误信息。

    最后定义 GridPanel ,代码如下:

            var grid = new Ext.grid.GridPanel({

                renderTo: 'grid1',

                frame: true,

                title: ' 一个结合 DataWrite RowEditor Grid 的示例 ',

                autoScroll: true,

                600,

                height: 500,

                store: store,

                plugins: [editor],

                columns : [

                                   {header: " 编号 ", 100, sortable: true, dataIndex: 'cid',

                                       editor: ideditor

                                   },

                                   {header: " 名称 ", 250, sortable: true, dataIndex: 'title',

                                       editor: new Ext.form.TextField({

                                               allowBlank: false     

                                       }

                                   )},

                                   {header: " 描述 ", 300, sortable: true, dataIndex: 'desc', editor: new Ext.form.TextField()}

                                       ],

                tbar: [{

                    text: ' 增加 ',

                    handler: function(){

                                       var u = new store.recordType({

                                           cid : '',

                                           title: '',

                                           desc : ''

                                       });

                                       editor.stopEditing();

                                       store.insert(0, u);

                                       editor.startEditing(0);

                    }

                }, {

                    text: ' 删除 ',

                    handler: function(){

                                       var rec = grid.getSelectionModel().getSelected();

                                       if (!rec) {

                                           return false;

                                       }

                                       grid.store.remove(rec);

                    }

                }],

                viewConfig: {

                    forceFit: true

                }

            });

    GridPanel 中,增加按钮用来在 Store 中创建一个新记录,然后激活 RowEditor ,进入编辑状态。删除按钮则获取选择记录,并从 Store 中删除该记录。

    现在要完成服务器端代码。

    VS 2008 中,创建一个名称为“ Grid.ashx ”的一般处理程序,然后添加以下引用:

    using Newtonsoft.Json;

    using Newtonsoft.Json.Linq;

    using ExtShop;

    using System.Linq;

    接着修改 processRequest 方法,其代码如下:

        public void ProcessRequest (HttpContext context) {

          string act = context.Request["act"] ?? "";

          string output = "";

          switch (act)

          {

            case "list":

              output = List(context.Request);

              break;

            case "create":

               output = Create(context.Request);

              break;

            case "update":

              output = Update(context.Request);

              break;

            case "del":

              output = Del(context.Request);

              break;

            default:

              output = "{success:false,msg:' 错误的访问类型。 '}";

              break;         

          }

          context.Response.ContentType="text/javascript";

          context.Response.Write(output);

        }

    代码将根据提交 act 参数执行对应的方法。

    首先完成 List 方法,其代码如下:

        private string List(HttpRequest request)

        {

           ExtShopDataContext dc = new ExtShopDataContext();    

          return new JObject(

            new JProperty("success", true),

            new JProperty("total", dc.T_Categories.Count()),

            new JProperty("msg", ""),

            new JProperty("rows", new JArray(

                from m in dc.T_Categories

                select new JObject(

                  new JProperty("id", m.CategoryID),

                  new JProperty("cid", m.CategoryID),

                  new JProperty("title",m.Titel),

                  new JProperty("desc",m.Description)

                  )

              ))

            ).ToString();

        }

    因为不考虑分页问题,所以直接使用 JSON to LINQ 输入结果就可以了,要注意的就是,需要输出 2 CategoryID 值。

    接着完成 Create 方法,其代码如下:

        private string Create(HttpRequest request)

        {

          string rows = request["rows"] ?? "";

          if (rows.Length > 0)

          {

            JObject r = JObject.Parse(rows);

            string id = (string)r["cid"] ?? "";

            string title = (string)r["title"] ?? "";

            string desc = (string)r["desc"] ?? "";

            if (id.Length > 0 & title.Length > 0)

             {

              try

              {

                ExtShopDataContext dc = new ExtShopDataContext();

                var q = dc.T_Categories.SingleOrDefault(m => m.CategoryID == id);

                if (q == null)

                {

                  T_Categories rec = new T_Categories();

                  rec.CategoryID = id;

                  rec.Titel = title;

                  rec.Description = desc;

                  dc.T_Categories.InsertOnSubmit(rec);

                  dc.SubmitChanges();

                  return new JObject(

                    new JProperty("success", true),

                    new JProperty("total", 0),

                    new JProperty("msg", rows),

                    new JProperty("rows", new JArray(

                        new JObject(

                            new JProperty("id", id),

                             new JProperty("cid", id),

                            new JProperty("title", title),

                            new JProperty("desc", desc)

                          )                     

                      ))

                    ).ToString();

                 }

                else

                {

                  return new JObject(

                    new JProperty("success", false),

                    new JProperty("msg", " 编号“ "+id+" ”已存在。 ")

                    ).ToString();

                }

              }

              catch (Exception e)

              {

                return new JObject(

                  new JProperty("success", false),

                  new JProperty("msg", e.Message)

                  ).ToString();           

              }

            }

            else

            {

              return new JObject(

                 new JProperty("success", false),

                new JProperty("msg", " 错误的提交数据。 ")

                ).ToString();

            }

          }

          else

          {

            return new JObject(

              new JProperty("success", false),

              new JProperty("msg"," 错误的提交数据。 ")

              ).ToString();

          }

        }

    因为提交的参数是“ rows ”(该参数由 Store 定义的参数 root 的值决定),且值为 JSON 格式的字符串,因而最简单的方式是先将字符串转换为 JSON 对象,然后再处理。转换后将值分别保存到 id title desc 三个变量里。

    保存成功一定要按 JsonStore 定义的格式返回数据,而且要返回新增的记录。如果是自动生成的 id ,需要获取并返回给 Store

    接着要完成 Update 方法,代码如下:

        private string Update(HttpRequest request)

        {

          string id = request["id"] ?? "";

          string rows = request["rows"] ?? "";

          if (rows.Length > 0)

          {

            JObject r = JObject.Parse(rows);

            string cid = (string)r["cid"] ?? "";

            string title = (string)r["title"] ?? "";

            string desc = (string)r["desc"] ?? "";

            if (title.Length <= 0)

            {

              return new JObject(

                new JProperty("success", false),

                new JProperty("total", 1),

                new JProperty("msg", " 请输入名称。 "),

                new JProperty("rows", new JArray(

                new JObject(

                    new JProperty("id", id),

                    new JProperty("cid", id),

                    new JProperty("title", title),

                    new JProperty("desc", desc)

                  )

                  ))

                ).ToString();

            }

            try

            {

              ExtShopDataContext dc = new ExtShopDataContext();

              var q = dc.T_Categories.SingleOrDefault(m => m.CategoryID.ToLower() == id.ToLower());

              if (q != null)

              {

                q.Titel = title;

                q.Description = desc;

                dc.SubmitChanges();

                return new JObject(

                  new JProperty("success", true),

                  new JProperty("total", 1),

                  new JProperty("msg", ""),

                  new JProperty("rows", new JArray(

                  new JObject(

                      new JProperty("id", id),

                      new JProperty("cid", id),

                      new JProperty("title", title),

                       new JProperty("desc", desc)

                    )

                    ))

                  ).ToString();

              }

              else

              {

                return new JObject(

                  new JProperty("success", false),

                  new JProperty("msg", " 编号“ "+id+" ”不存在或已被删除。 "),

                      new JProperty("rows", new JArray(

                      new JObject(

                          new JProperty("id", id),

                          new JProperty("cid", id),

                          new JProperty("title", title),

                          new JProperty("desc", desc)

                        )                                             

                        ))

                  ).ToString();

              }

            }

            catch (Exception e)

            {

              return new JObject(

                new JProperty("success", false),

                new JProperty("msg", e.Message),

                      new JProperty("rows", new JArray(

                      new JObject(

                          new JProperty("id", id),

                          new JProperty("cid", id),

                          new JProperty("title", title),

                          new JProperty("desc", desc)

                        )

                        ))

                ).ToString();           

            }

          }

          else

          {

            return new JObject(

              new JProperty("success", false),

              new JProperty("msg"," 错误的提交数据。 ")

              ).ToString();

          }

        }

    Update 方法中,无论是返回错误信息还是成功信息,都要以 Store 中定义好的 JSON 格式返回,而且必须返回更新的记录,不然 Store 在确认记录时,会认为该条记录不存在而删除该记录,然后向服务器提交删除该记录的请求。关于这一点,在已存在数据的情况下进行调试时一定要小心,不然会误删数据。

    Update 方法中还要注意,要更新记录的 id 会通过参数 id 提交,“ rows ”里提交的是更新的数据。

    最后完成的是 Del 方法,其代码如下:

        private string Del(HttpRequest request)

        {

          string id= request["rows"] ?? "";

          try

          {

            id = id.Replace("/"", "");

            ExtShopDataContext dc = new ExtShopDataContext();

            var q = dc.T_Categories.SingleOrDefault(m=>m.CategoryID.ToLower()==id.ToLower());

            if (q != null)

            {

              id = q.CategoryID;

              dc.T_Categories.DeleteOnSubmit(q);

              dc.SubmitChanges();

            }

            return new JObject(

              new JProperty("success", true),

              new JProperty("msg", " 删除编号为“ " + id + " ”的记录成功。 ")

              ).ToString();

          }

          catch(Exception e)

          {

            return new JObject(

               new JProperty("success", false),

              new JProperty("msg", e.Message)

              ).ToString();       

          }

        }

    Del 方法中,记录的 id 也是以参数“ rows ”提交的。返回的数据格式就不用 Store 定义的 JSON 格式返回了。

  • 相关阅读:
    什么是 go vendor
    Golang包管理工具之govendor的使用
    国内的go get问题的解决
    集群、限流、缓存 BAT 大厂无非也就是这么做
    Gin框架中文文档
    GO——beego简单开发实例(二)
    C++11 并发指南四(<future> 详解一 std::promise 介绍)(转)
    C++11 并发指南三(std::mutex 详解)(转)
    C++11 并发指南二(std::thread 详解)(转)
    用C++设计一个不能被继承的类(转)
  • 原文地址:https://www.cnblogs.com/hainange/p/6334332.html
Copyright © 2020-2023  润新知