Extjs巧用Grid

前两天用Extjs4.0做了可编辑的grid,在这里和大家分享一下
 
1、目标:实现试题管理
 
2、代码试题添加部分代码如下:
 




/// <reference path="../Ext4.0/ext-all.js" />






/**********************************************/
/*选项列表*/



// Define our data model
Ext.define('SubjectOption', {
    extend: 'Ext.data.Model',
    fields: [

            { name: 'SubjectID', type: 'string' },
            { name: 'Item', type: 'string' },
            { name: 'ItemContent', type: 'string' }
        ]
});



var optionStore = Ext.create('Ext.data.Store', {
    // destroy the store if the grid is destroyed
    autoDestroy: true,
    model: 'SubjectOption',
    remoteSort: false,
    proxy: {
        type: 'ajax',
        //url: "Authority/GetAuthority",
        //   url: "Examlib/GetExamlibs",
        actionMethods: 'post',
        reader: {
            type: 'json',
            root: 'data'
        }
    }
});

var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
    clicksToMoveEditor: 1,
    autoCancel: false
});


var sm = Ext.create('Ext.selection.CheckboxModel', {
    dataIndex: "Item"
});
// create the grid and specify what field you want
// to use for the editor at each column.
var optionGrid = Ext.create('Ext.grid.Panel', {
    selModel: sm,
    store: optionStore,
    id: "optionGrid",
    autoHeight: true,
    width:340,
    baseCls: "x-panel",
    multiSelect: true,
    height: document.documentElement.clientHeight * 3 / 8,
    columns: [{
        header: 'SubjectID',
        dataIndex: 'SubjectID',
        hidden: true
    }, {
        header: '選項',
        dataIndex: 'Item',
        width: 50,
        field: {
            xtype: 'textfield'
        }
    }, {
        header: '選項內容',
        dataIndex: 'ItemContent',
        flex: 1,
        field: {
            xtype: 'textfield'
        }
    }],


    frame: true,
    dockedItems: [{
        dock: 'top',
        xtype: 'toolbar',
        items: [
                  {
                      text: '新增',
                      iconCls: 'addicon',
                      handler: function () {
                          rowEditing.cancelEdit();

                          // Create a model instance


                          optionStore.insert(0, new SubjectOption());
                          rowEditing.startEdit(0, 0);
                      }
                  }, {
                      itemId: 'remove',
                      text: '刪除',
                      iconCls: 'deleteicon',
                      handler: function () {
                          var sm = optionGrid.getSelectionModel();
                          rowEditing.cancelEdit();
                          optionStore.remove(sm.getSelection());
                          if (optionStore.getCount() > 0) {
                              sm.select(0);
                          }
                      },
                      disabled: true
                  }]
    }],
    plugins: [rowEditing],

    listeners: {
        'selectionchange': function (view, records) {
            optionGrid.down('#remove').setDisabled(!records.length);

        }
    }
}
    );



/**********************************************/
/******************************************************/
/**下拉框**/
var typeStore = Ext.create('Ext.data.Store', {
    fields: ['Name', 'Value'],
    data: [
        { "Name": "單選題", "Value": "1" },
        { "Name": "複選題", "Value": "2" },
        { "Name": "是非題", "Value": "3" }
    ]
});
var levelStore = Ext.create('Ext.data.Store', {
    fields: ['Name', 'Value'],
    data: [
        { "Name": "簡單", "Value": "1" },
        { "Name": "中等", "Value": "2" },
        { "Name": "困難", "Value": "3" }
    ]
});
/****************************************************/
/*選擇不同試題類型,默認出現選項*/

var TypeComboBox = Ext.create('Ext.form.ComboBox', {
    fieldLabel: '試題類型',
    border: 0,
    id: "Type",
    labelWidth: 100,
    store: typeStore,
    mode: "local",
    value: "1",
    queryMode: 'local',
    displayField: 'Name',
    valueField: 'Value',
    triggerAction: "all",
    listeners: {
        "select": function (combo, record) {
            try {
                var optionStore = Ext.getCmp("optionGrid").store;
                optionStore.removeAll();
                if (combo.getValue() == '1') {
                    optionStore.add({ SubjectID: '', Item: 'A', ItemContent: '' }, { SubjectID: '', Item: 'B', ItemContent: '' }, { SubjectID: '', Item: 'C', ItemContent: '' }, { SubjectID: '', Item: 'D', ItemContent: '' });
                }
                else if (combo.getValue() == '2') {
                    optionStore.add({ SubjectID: '', Item: 'A', ItemContent: '' }, { SubjectID: '', Item: 'B', ItemContent: '' }, { SubjectID: '', Item: 'C', ItemContent: '' }, { SubjectID: '', Item: 'D', ItemContent: '' }, { SubjectID: '', Item: 'E', ItemContent: '' });
                }
                else {
                    optionStore.add({ SubjectID: '', Item: '是', ItemContent: '' }, { SubjectID: '', Item: '否', ItemContent: '' });
                }

            }
            catch (ex) {
                Ext.MessageBox.alert("错误", "数据加载失败。");
            }
        },
        beforequery: function (qe) {

        }
    }
});



/**********************************************/

AddInfos = function () {



    var AddInfoForm = Ext.create('Ext.form.Panel', {
        width: 350,
        height: document.documentElement.clientHeight * 1 / 4,
        plain: true,
        frame: true,
        id: "frmAdd",
        labelWidth: 45,
        defaultType: "textfield",
        baseCls: "x-plain",
        layout: 'anchor',
        defaults: { anchor: "95%", msgTarget: "side" },
        url: "Subject/Add",
        bodyStyle: 'padding:5px 0px 0px 5px',
        // The fields
        defaultType: 'textfield',
        items: [
           {
              id: "Level",
              name: "Level",
              xtype: "combo",
              fieldLabel: "級別",
              //传入后台真实值value field /value
              //hiddenName:"abcd",
              //readOnly: true,
              mode: "local",
              displayField: "Name",
              valueField: "Value",
              triggerAction: "all",
              value: "1",
              store: levelStore
          }, TypeComboBox, {
              fieldLabel: '試題內容',
              height:50,
              xtype: 'textareafield',
              id: "Content",
              name: 'Content',
              allowBlank: false,
              blankText: "試題內容不能為空"
          }, {
              id: 'Key',
              fieldLabel: '答案',
              name: 'Key',
              hidden: true
          }]
    });

    /*加入保存按鈕*/


    var btnSave = Ext.create('Ext.Button', {
        text: '保存',
        buttonAlign: "center",
        width: 60,
        listeners: {
            click: function () {

                /*獲得輸入值*/
                var Content = Ext.getCmp("Content").getValue();
                var Level = Ext.getCmp("Level").getValue();
                var Type = Ext.getCmp("Type").getValue();
                var Key = Ext.getCmp("Key").getValue();

                /*獲得選項grid*/
                var optionGrid = Ext.getCmp("optionGrid");

                /*選中的行為答案*/
                var checkedrow = optionGrid.getSelectionModel().getSelection();
                for (var i = 0; i < checkedrow.length; i++) {
                    if (checkedrow.length == 1) {
                        Key = checkedrow[i].data.Item;
                    }
                    else {

                        if (i < (checkedrow.length - 1)) {
                            Key = checkedrow[i].data.Item + "," + Key;
                        }
                        if (i == (checkedrow.length - 1)) {
                            Key = Key + checkedrow[i].data.Item;
                        }
                    }
                }

                /*保存選項,產生json*/
                var arr = new Array();
                optionGrid.store.each(function (record) {
                    arr.push(record.data);
                }); ;
                var json = Ext.encode(arr);

                /*提交保存*/

                var form = Ext.getCmp('frmAdd').getForm();
                if (form.isValid()) {
                    Ext.Ajax.request({
                        url: "http://www.cnblogs.com/Subject/Add",
                        method: "POST",
                        params: {
                            Content: Content,
                            Level: Level,
                            Type: Type,
                            Key: Key,
                            json: json
                        },
                        success: function (form, action) {
                            //重新載入試題grid
                            var result = Ext.decode(form.responseText);
                            Ext.Msg.alert("恭喜", result.msg);

                            AddWin.hide();
                            store.load();
                        },
                        failure: function () {
                            Ext.Msg.alert("提 示", "新增失败!");
                        }
                    });
                }
            }
        }
    });
    /**********************************************/

    var AddWin = Ext.create('Ext.window.Window', {
        title: '新增試題',
        width: 350,
        height: 350,

        labelWidth: 100,
        closeAction: 'hide',
        resizable: false,
        modal: 'true',
        border: 0,
        iconCls: "editicon",
        items: [
            AddInfoForm, optionGrid],

        buttonAlign: "center",
        bodyStyle: 'padding:0px 0px 0px 0px',
        buttons: [btnSave],
        listeners: {
            "show": function () {
                optionStore.removeAll();
                optionStore.add({ SubjectID: '', Item: 'A', ItemContent: '' }, { SubjectID: '', Item: 'B', ItemContent: '' }, { SubjectID: '', Item: 'C', ItemContent: '' }, { SubjectID: '', Item: 'D', ItemContent: '' });
            }
        }
    });
    AddWin.show();
}
 
 
 
3、效果图
 
 
 
 
(1)添加试题选时,需要将grid中的store 序列化成Json,Extjs内部有方法
 
    /*保存選項,產生json*/
                var arr = new Array();
                optionGrid.store.each(function (record) {
                    arr.push(record.data);
                }); ;
                var json = Ext.encode(arr);
 
这样就传到后台
 
.net通过方法Deserialize解析传入的json
成为泛型集合类
 
 

public  T Deserialize<T>(string sJson) where T : class
          {
              DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));
              MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(sJson));
              T obj = (T)ds.ReadObject(ms);

              ms.Close();
              return obj;
          }
 
调用如下
 
List<SubjectOption> options = jsonHelper.Deserialize<List<SubjectOption>>(json);
 

 

(2)可编辑grid
 
 
 
                        text: '新增',
                      iconCls: 'addicon',
                      handler: function () {
                          rowEditing.cancelEdit();

                          // Create a model instance


                          optionStore.insert(0, new SubjectOption());
                          rowEditing.startEdit(0, 0);
                      }

 

 
 
 
 
 
 
 
 
 
 
 





posted @ 2012-07-03 17:36  .windy  阅读(872)  评论(0编辑  收藏  举报