第三节:ExtJS调用WCF系列-----添加,修改,删除

我们继续上一节中的那个项目,给那个员工列表增加 添加修改删除功能。和上一节一样,我们先从服务器端说起,服务器端需要提供WCF接口给客户端调用,我们先来写几个BLL的数据处理方法

 

/// <summary>
        
/// 获取部门列表
        
/// </summary>
        
/// <returns></returns>

        public string GetDeptList()
        
{
            var query 
= from dept in ctx.Department
                        select 
new
                        
{
                            DeptID 
= dept.DepartmentID,
                            DeptName 
= dept.CnName
                        }
;
            
return @"{""DeptList"":"+query.ToJSON()+"}";
        }

        
/// <summary>
        
/// 添加员工
        
/// </summary>
        
/// <param name="emp"></param>
        
/// <returns></returns>

        public string AddEmployee(Employee emp)
        
{
            
try
            
{
                ctx.Employee.InsertOnSubmit(emp);
                ctx.SubmitChanges();
                
return "员工:" + emp.CnName + " 添加成功!";
            }

            
catch(Exception ex)
            
{
                
return "员工:" + emp.CnName + " 添加失败!" + ex.Message; 
            }

        }

        
public Employee GetEmployee(int empid)
        
{
            
return ctx.Employee.Single(it => it.EmployeeID == empid);
        }

        
/// <summary>
        
/// 修改员工
        
/// </summary>
        
/// <param name="emp"></param>
        
/// <returns></returns>

        public string UpdateEmployee(Employee emp)
        
{
            Employee Originalemp 
= ctx.Employee.Single(it => it.EmployeeID == emp.EmployeeID);
            Originalemp.EmployeeID 
= emp.EmployeeID;
            Originalemp.CnName 
= emp.CnName;
            Originalemp.Sex 
= emp.Sex;
            Originalemp.Age 
= emp.Age;
            Originalemp.Email 
= emp.Email;
            Originalemp.OnWorkDate 
= emp.OnWorkDate;
            Originalemp.DepartmentID 
= emp.DepartmentID;
            
try
            
{
                ctx.SubmitChanges();
                
return "员工:" + emp.CnName + " 修改成功!";
            }

            
catch (Exception ex)
            
{
                
return "员工:" + emp.CnName + " 修改失败!" + ex.Message;;
            }

        }

        
/// <summary>
        
/// 根据员工ID数组删除员工
        
/// </summary>
        
/// <param name="EmpIDArr"></param>
        
/// <returns></returns>

        public string DelEmployee(Array EmpIDArr)
        
{
            List
<Employee> emplist = new List<Employee>();
            
foreach (int empid in EmpIDArr)
            
{
                Employee emp 
= ctx.Employee.Single(it => it.EmployeeID == empid);
                emplist.Add(emp);
            }

            
try
            
{
                ctx.Employee.DeleteAllOnSubmit(emplist);
                ctx.SubmitChanges();
                
return EmpIDArr.Length + "个员工删除成功!";
            }

            
catch (Exception ex)
            
{
                
return EmpIDArr.Length + "个员工删除失败!" + ex.Message; 
            }

        }


然后在EmployeeService.svc文件中把这几个方法封装WCF接口

 第三节

 

这样服务器端的工作就完成了,下面到客户端.也就是EXTJS的代码编写,这里要注意两个问题:
一个是关于WCF传递过来的日期型数据和从EXTJS的form中取得的日期型数据相互转化的问题,WCF传递过来的日期形式为“\/Date(62831853071)\/”括号里面的数字是UTC时间,我们需要设置Ext.form.DateField的format : "Y-m-d",然后把两种类型在通讯之前进行相互转化。
第二个是当BodyStyle = WebMessageBodyStyle.Wrapped 的时候WCF会自动把传递过来的值进行封装,这个在第二节的时候有详细说明,在把WCF传过来的值转化为ExtJS需要的对象的时候去掉这个封装。
基于以上两点,我写了一个WCFHelper.js的文件,代码如下:


/**
 * Author by xiaozhuang  iamxiazhuang@hotmail.com
 * Date 2007-12-14
 
*/

 
/**
 *ConvertResponseText:转化从WCF获取的Object转化为ExtJS表单需要的Object
 *responsetext:从WCF获取的ObjectJSON字符串
 *datefieldname:JSon中的日期型字段名(属性名),多个用","分开
 *wrapped:JSon字符串是否被封装(WebMessageBodyStyle.Wrapped or WebMessageBodyStyle.Bare)
 *ResultObject :返回值 Object
 
*/

  
function ConvertResponseText(responsetext,datefieldname,wrapped,isobject)
        
var ResultObject;
        
var obj = eval("("+responsetext+")");
        
if (wrapped)
        
{
         
for (var prop in obj) {  
              
if (typeof(prop) == 'string' && prop.substr(prop.length-6,prop.length) == 'Result') {  //去掉××Result 封装
                   if(isobject){
                        ResultObject 
= ConvertResponseDetail(obj[prop],datefieldname); 
                    }
 else {
                        ResultObject 
= obj[prop]; 
                    }

                  
break
              }
 
          }
 
          }

          
else
          
{
             
if(isobject){
                  ResultObject 
= ConvertResponseDetail(obj,datefieldname); 
             }
 else {
                 ResultObject 
= obj; 
             }

          }

         
return ResultObject;
  }

    
/***私有方法**/
    
function ConvertResponseDetail(obj,datefieldname){  
         
var newResult = new Object(); 
         
for (var rootProp in obj) {  
         
if(datefieldname.indexOf(rootProp) != -1){
              
var dt = eval("new " + obj[rootProp].substr(1,obj[rootProp].length-2)); //对UTC日期进行转化
              newResult[rootProp] = DateToStr(dt);//把日期转化为字符串
         }

         
else{
              newResult[rootProp] 
= obj[rootProp]; 
             }
 
         }
  
         
return newResult;  
      }

      
/***私有方法**/  
     
function DateToStr(dt){
            
var str = "";
            
if(dt.getFullYear){
              
var y,m,d;
              y 
= dt.getFullYear();
              m 
= dt.getMonth()+1;  //01-12
              d = dt.getDate();
              m 
= m>9?m:"0"+m;
              d 
= d>9?d:"0"+d;
              str
= y+"-"+m+"-"+d;
            }

            
return str;
     }

 
/**
 * Author by xiaozhuang  iamxiazhuang@hotmail.com
 * Date 2007-12-14
 
*/

 
/**
 *ConvertFormValues:转化从表单获取的值(Object)对象为WCF需要的Object
 *formvalue:从表的获取的值Object
 *datefieldname:表单值的日期型字段名,多个用","分开
 *ResultObject :返回值 Object
 
*/

     
function ConvertFormValue(formvalue,datefieldname){  
         
var ResultObject = new Object(); 
         
for (var prop in formvalue) {  
         
if(datefieldname.indexOf(prop) != -1){
              
var dt = StrToDate(formvalue[prop]); //字符串转化为日期
              ResultObject[prop] = "\/Date("+Date.UTC(dt.getFullYear(),dt.getMonth(),dt.getDate())+")\/"//转化为UTC日期
         }

         
else if (formvalue[prop] != ""){
              ResultObject[prop] 
= formvalue[prop]; 
             }
 
         }
  
         
return ResultObject;  
      }
  
     
/***私有方法**/    
     
function StrToDate(str){
          
var arys = new Array();
          arys
=str.split('-');
          
var newDate=new Date(arys[0],arys[1]-1,arys[2]); 
          
return newDate;
     }
 

 

接下来编写paging.js代码,主要用到了Ext.FormPanel和Ext.Window 两个控件来提供编辑和添加界面,paging.js的所有代码如下,包括前一节的那部分。

/*

 * Author by Xiaozhuang

 * 

 * 
 
*/

Ext.onReady(
function(){
   
    
// create the Data Store
    var store = new Ext.data.Store({
        
// load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.WCFHttpProxy({
            url: '
/EmployeeService.svc/GetEmployeePaging'
        }
),
     
        
// create reader that reads the Topic records
        reader: new Ext.data.WCFJsonReader({
            root: 'EmployeeList',
            totalProperty: 'TotalCount',
            id: 'EmployeeID',
            fields: [
                
{name: 'EmployeeID', type: 'int'},
                
{name: 'CnName', type: 'string'},
                
{name: 'Sex', type: 'string'},
                
{name: 'Age', type: 'int'},
                
{name: 'Email', type: 'string'},
                
{name: 'OnWorkDate',type:'string'},
                
{name: 'DeptName', type: 'string'}
            ]
        }
),

        
// turn on remote sorting
        remoteSort: true
    }
);
    
    store.setDefaultSort('EmployeeID', 'ASC');

    
// 把true和false转化为男或者女,这个其实可以在服务器端进行转化,写在这里只是为了测试
    function renderSex(value, p, record){
    
return record.data.Sex=="true"?"":"";
    }

    
//这个函数演示了怎样把服务器端的DateTime类型转为Javascript的日期
    function renderOnWorkDate(value, p, record){
        
var jsondate = record.data.OnWorkDate;
       
return eval("new " + jsondate.substr(1,jsondate.length-2)).toLocaleDateString();
    }


    
// the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store
    var nm = new Ext.grid.RowNumberer();
    
var sm = new Ext.grid.CheckboxSelectionModel();  // add checkbox column

    
var cm = new Ext.grid.ColumnModel([nm,sm,{
           header: 
"员工ID",
           dataIndex: 'EmployeeID',
           width: 
100
//           renderer: renderTopic
       }
,{
           header: 
"姓名",
           dataIndex: 'CnName',
           width: 
200
        }
,{
           header: 
"性别",
           dataIndex: 'Sex',
           width: 
70,
           renderer: renderSex
        }
,{
           header: 
"年龄",
           dataIndex: 'Age',
           width: 
70
           
        }
,{
         header: 
"Email",
           dataIndex: 'Email',
           width: 
150
        }
,{
           header: 
"入职时间",
           dataIndex: 'OnWorkDate',
           width: 
150,
           renderer: renderOnWorkDate
        }
,{
           header: 
"部门",
           dataIndex: 'DeptName',
           width: 
200
          
        }
]);

    
// by default columns are sortable
    cm.defaultSortable = true;

    
var grid = new Ext.grid.GridPanel({
        
//el:'topic-grid',
        renderTo: document.body,
        width:
800,
        height:
500,
        title:'分页和排序列表',
        store: store,
        cm: cm,
        trackMouseOver:
false,
        sm: sm,
        loadMask: 
true,
        viewConfig: 
{
            forceFit:
true,
            enableRowBody:
true,
            showPreview:
true,
            getRowClass : 
function(record, rowIndex, p, store){
               
                
return 'x-grid3-row-collapsed';
            }

        }
,
         
// inline toolbars
        tbar:[{
            text:'添加',
            tooltip:'添加一条记录',
            iconCls:'add',
            handler:handleAdd
        }
, '-', {
            text:'修改',
            tooltip:'修改',
            iconCls:'option',
            handler:handleEdit
        }
,'-',{
            text:'删除',
            tooltip:'删除记录',
            iconCls:'remove',
            handler:handleDelete
        }
],
        bbar: 
new Ext.PagingToolbar({
            pageSize: 
25,
            store: store,
            displayInfo: 
true
        }
)
    }
);
  
    
// render it
    grid.render();
   

    
// trigger the data store load
    var request={start:0,limit:25};
    store.load(
{params:request});
    
    
//获取部门列表
      var deptDs = new Ext.data.Store({
        proxy: 
new Ext.data.WCFHttpProxy({
            url:'
/EmployeeService.svc/GetDeptList'
        }
),
        reader: 
new Ext.data.WCFJsonReader({
                    root: 'DeptList',
                    id: 'DeptID'
                    }
, [ 'DeptID', 'DeptName']
                ),
        remoteSort: 
false
      }
);
   
    
    
//员工信息表单
     var EmpForm = new Ext.FormPanel({
        frame: 
true,
        labelAlign: 'right',
        labelWidth: 
120,
        width: 
450,
        height:
250,
        items: 
new Ext.form.FieldSet({
                title: '员工资料',
                autoHeight: 
true,
                defaults: 
{width: 200},
                defaultType: 'textfield',
        items: [
new Ext.form.Hidden({
                name: 'EmployeeID'
            }
),{
                fieldLabel: '姓名',
                name: 'CnName',
                allowBlank:
false
            }
,new Ext.form.ComboBox({
                fieldLabel: '性别',
                hiddenName:'Sex',
                store: 
new Ext.data.SimpleStore({
                    fields: ['value', 'text'],
                    data : [[
1,'男'],[0,'女']]
                }
),
                valueField:'value',
                displayField:'text',
                typeAhead: 
true,
                mode: 'local',
                triggerAction: 'all',
                selectOnFocus:
true,
                allowBlank:
false
            }
),new Ext.form.NumberField({
                fieldLabel: '年龄',
                name: 'Age'
            }
), {
                fieldLabel: 'Email',
                name: 'Email',
                vtype:'email'
            }
new Ext.form.DateField({
                            fieldLabel: '入职时间',
                            name: 'OnWorkDate',
                            allowBlank:
false,
                            format : 
"Y-m-d"
            }
), new Ext.form.ComboBox({
                            fieldLabel: '所属部门',
                            name: 'DepartmentName',
                            hiddenName: 'DepartmentID',
                            store: deptDs,
                            valueField: 'DeptID',
                            displayField: 'DeptName',
                            typeAhead: 
true,
                            mode: 'remote',
                            triggerAction: 'all',
                            emptyText: '请选择部门',
                            selectOnFocus: 
true,
                            allowBlank: 
false
                        }
)
            ]
         }
)
    }
);
   
    
     
function handleAdd(){
       
var AddEmpWin = new Ext.Window({
                title: '增加新员工',
                layout:'fit',
                width:
500,
                height:
300,
                plain: 
true,
                items:EmpForm,
                buttons: [
{
                    text:'保存',
                    handler: AddRecord
                }
,{
                    text: '取消',
                    handler: 
function(){
                        AddEmpWin.hide();
                    }

                }
]
     }
);
        AddEmpWin.show(
this);
    }
  
    
function handleEdit(){
     
var selectedKeys = grid.selModel.selections.keys; //returns array of selected rows ids only
            if(selectedKeys.length != 1){
                Ext.MessageBox.alert('提示','请选择一条记录!');
            }
    
            
else {
            
var EditEmpWin = new Ext.Window({
                title: '修改员工资料',
                layout:'fit',
                width:
500,
                height:
300,
                plain: 
true,
                items:EmpForm,
                buttons: [
{
                    text:'保存',
                    handler: UpdateRecord
                }
,{
                    text: '取消',
                    handler: 
function(){
                        EditEmpWin.hide();
                    }

                }
]
     }
);
        EditEmpWin.show(
this);
        
//Ext.MessageBox.alert("提示",selectedKeys);
          deptDs.load(); //取得科室列表
        var request = {empID:selectedKeys[0]};
             Ext.MessageBox.show(
{
                           msg: '正在请求数据, 请稍侯',
                           progressText: '正在请求数据',
                           width:
300,
                           wait:
true,
                           waitConfig: 
{interval:200}
                     }
);
            Ext.Ajax.request(
{
                    url: '
/EmployeeService.svc/GetEmployee', //url to server side script
                    method: 'POST', 
                    params:Ext.util.JSON.encode(request),
//the unique id(s)
                    callback: function (options, success, response) {
                        
if (success) //success will be true if the request succeeded
                              Ext.MessageBox.hide();
                              
var formvalue=ConvertResponseText(response.responseText,"OnWorkDate",true,true);
                              EmpForm.form.setValues(formvalue);
                        }
 else {
                             Ext.MessageBox.hide();
                             Ext.MessageBox.alert(
"失败,请重试",response.responseText);
                        }

                    }
,
                    
//the function to be called upon failure of the request (server script, 404, or 403 errors)
                    failure:function(response,options){
                        Ext.MessageBox.hide();
                        ReturnValue 
= Ext.MessageBox.alert("警告","出现异常错误!请联系管理员!");
                    }
,  
                    success:
function(response,options){
                        Ext.MessageBox.hide();
                    }
                                    
          }
)// end Ajax request 
        }

    }
  
    
function UpdateRecord(btn)
    
{
        
if (EmpForm.form.isValid()) {
                btn.disabled
=true;
                Ext.MessageBox.show(
{
                       msg: '正在请求数据, 请稍侯',
                       progressText: '正在请求数据',
                       width:
300,
                       wait:
true,
                       waitConfig: 
{interval:200}
                 }
);
                 
var formvalue = EmpForm.form.getValues();
                 
var request = {emp:ConvertFormValue(formvalue,'OnWorkDate')};
                 
//Ext.MessageBox.alert("提示",formvalues); 
                Ext.Ajax.request({
                        url: '
/EmployeeService.svc/UpdateEmployee', //url to server side script
                        method: 'POST', 
                        params:Ext.util.JSON.encode(request),
//the unique id(s)
                        callback: function (options, success, response) {
                            
if (success) //success will be true if the request succeeded
                                  Ext.MessageBox.hide();
                                  
var alertcontent=ConvertResponseText(response.responseText,"",true,false);
                                  Ext.MessageBox.alert(
"成功",alertcontent);
                            }
 else {
                                 Ext.MessageBox.hide();
                                 Ext.MessageBox.alert(
"失败,请重试",response.responseText);
                            }

                        }
,
                        
//the function to be called upon failure of the request (server script, 404, or 403 errors)
                        failure:function(response,options){
                            Ext.MessageBox.hide();
                            ReturnValue 
= Ext.MessageBox.alert("警告","出现异常错误!请联系管理员!");
                        }
,  
                        success:
function(response,options){
                            Ext.MessageBox.hide();
                            store.reload();
                        }
                                    
              }
)// end Ajax request 
         }

    }
    
    
    
function AddRecord(btn)
    
{
        
if (EmpForm.form.isValid()) {
          btn.disabled
=true;
                   Ext.MessageBox.show(
{
                       msg: '正在请求数据, 请稍侯',
                       progressText: '正在请求数据',
                       width:
300,
                       wait:
true,
                       waitConfig: 
{interval:200}
                 }
);
                 
var formvalue = EmpForm.form.getValues();
                 
var request = {emp:ConvertFormValue(formvalue,'OnWorkDate')};
                 
//Ext.MessageBox.alert("提示",formvalues); 
                Ext.Ajax.request({
                        url: '
/EmployeeService.svc/AddEmployee', //url to server side script
                        method: 'POST', 
                        params:Ext.util.JSON.encode(request),
//the unique id(s)
                        callback: function (options, success, response) {
                            
if (success) //success will be true if the request succeeded
                                  Ext.MessageBox.hide();
                                  
var alertcontent=ConvertResponseText(response.responseText,"",true,false);
                                  Ext.MessageBox.alert(
"成功",alertcontent);
                            }
 else {
                                 Ext.MessageBox.hide();
                                 Ext.MessageBox.alert(
"失败,请重试",response.responseText);
                            }

                        }
,
                        
//the function to be called upon failure of the request (server script, 404, or 403 errors)
                        failure:function(response,options){
                            Ext.MessageBox.hide();
                            ReturnValue 
= Ext.MessageBox.alert("警告","出现异常错误!请联系管理员!");
                        }
,  
                        success:
function(response,options){
                            Ext.MessageBox.hide();
                            store.reload();
                        }
                                    
              }
)// end Ajax request 
                
        }

    }

    
    
function handleDelete(){
      
var selectedKeys = grid.selModel.selections.keys; //returns array of selected rows ids only
            if(selectedKeys.length > 0)
            
{
                Ext.MessageBox.confirm('提示','您确实要删除选定的记录吗?', deleteRecord);
            }

            
else
            
{
                Ext.MessageBox.alert('提示','请至少选择一条记录!');
            }
//end
    }
  
   
    
function deleteRecord(btn){
         
if(btn=='yes'){
              
var selectedRows = grid.selModel.selections.items;//returns record objects for selected rows (all info for row)
                var selectedKeys = grid.selModel.selections.keys; 
                
//var deleteresult = AjaxRequest('/EmployeeService.svc/DelEmployee',selectedKeys,false,"")
                Ext.MessageBox.show({
                       msg: '正在请求数据, 请稍侯',
                       progressText: '正在请求数据',
                       width:
300,
                       wait:
true,
                       waitConfig: 
{interval:200}
                 }
);
                Ext.Ajax.request(
{
                        url: '
/EmployeeService.svc/DelEmployee', //url to server side script
                        method: 'POST', 
                        params:Ext.util.JSON.encode(selectedKeys),
//the unique id(s)
                        callback: function (options, success, response) {
                            
if (success) //success will be true if the request succeeded
                                  Ext.MessageBox.hide();
                                   
var alertcontent=ConvertResponseText(response.responseText,"",false,false);
                                  Ext.MessageBox.alert(
"成功",alertcontent);
                            }
 else {
                                 Ext.MessageBox.hide();
                                 Ext.MessageBox.alert(
"失败,请重试",response.responseText);
                            }

                        }
,
                        
//the function to be called upon failure of the request (server script, 404, or 403 errors)
                        failure:function(response,options){
                            Ext.MessageBox.hide();
                            ReturnValue 
= Ext.MessageBox.alert("警告","出现异常错误!请联系管理员!");
                        }
,  
                        success:
function(response,options){
                            Ext.MessageBox.hide();
                            store.reload();
                        }
                                    
              }
)// end Ajax request 
         }
//end if click 'yes' on button
    }
 // end deleteRecord

        
   
}
);

 

运行效果:





源代码下载
数据库脚本

posted on 2007-12-18 12:59  小庄  阅读(10050)  评论(39编辑  收藏  举报