第一节:ExtJS调用WCF系列-----实现JSON传递

首先我们打开我们的VS 新建一个Asp.Net WebApplication Project,(不要给我说新建网站,我讨厌那个东东) 命名为ExtJSAndWCFChapter1 如图:

接下来我们在该项目中新建一个实体类文件和一个AJAX—Enabled WCF SERVICE,分别命名为Employee.cs 和EmployeeService.svc

下面去ExtJS.Com网站下载一个ExtJS 2.0 ,解压缩后拷贝至Default.aspx相同目录下,并包括在项目中。如图:

下面开始编写代码:先编写Employee.cs的代码,代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Runtime.Serialization;

namespace ExtJSAndWCFChapter1
{
    [DataContract]
    
public class Employee
    
{
            [DataMember]
            
public Guid EmployeeID setget; }
            [DataMember]
            
public string CnName setget; }
            [DataMember]
            
public bool Sex setget; }
            [DataMember]
            
public int Age setget; }
            [DataMember]
            
public DateTime Birthday setget; }
            [DataMember]
            
public string Email setget; }
        
    }

}


接下来编写EmployeeService.cs的代码,代码如下:
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Collections.Generic;

namespace ExtJSAndWCFChapter1
{
    [ServiceContract(Namespace 
= "")]
    [AspNetCompatibilityRequirements(RequirementsMode 
= AspNetCompatibilityRequirementsMode.Allowed)]
    
public class EmployeeService
    
{
        
// Add [WebGet] attribute to use HTTP GET
        [OperationContract]
        
public void DoWork()
        
{
            
// Add your operation implementation here
            return;
        }


        
// Add more operations here and mark them with [OperationContract]
        /// <summary>
        
/// 创建一个实体,实体由客户端传递
        
/// </summary>
        
/// <param name="emp"></param>
        
/// <returns></returns>

        [OperationContract]
        [WebInvoke(BodyStyle 
= WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Create")]  
        
public Guid Create(Employee emp)
        
{
            NotNull(emp.CnName, 
"CnName");
            
return Guid.NewGuid();
        }


        
/// <summary>
        
/// 获取一个实体
        
/// </summary>
        
/// <param name="id"></param>
        
/// <returns></returns>

        [OperationContract]
        [WebInvoke(BodyStyle 
= WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Get")]
        
public Employee Get(int id)
        
{
            
if (id != 1throw new ArgumentException("Expected 1 for ID");
            
return new Employee() { EmployeeID = Guid.NewGuid(), CnName = "Xiaozhuang", Sex = true, Age = 28, Email = "iamxiaozhuang@163.com", Birthday = new DateTime(19790202) };
        }


        
/// <summary>
        
/// 获取所有实体
        
/// </summary>
        
/// <returns></returns>

        [OperationContract]
        [WebInvoke(BodyStyle 
= WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetAll")]
        
public List<Employee> GetAll()
        
{
            
return new List<Employee>
            
{
                
new Employee(){EmployeeID = Guid.NewGuid(),CnName="CnName",Sex=true,Age=28,Email="email@saf.com",Birthday=new DateTime(1979,02,02)},
                
new Employee(){EmployeeID = Guid.NewGuid(),CnName="CnName1",Sex=false,Age=28,Email="email1@saf.com",Birthday=new DateTime(1979,02,02)}
            }
;
        }


        
/// <summary>
        
/// 获取num个实体
        
/// </summary>
        
/// <param name="num"></param>
        
/// <returns></returns>

        [OperationContract]
        [WebInvoke(BodyStyle 
= WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetByNum")]
        
public List<Employee> GetByNum(int num)
        
{
            
if (num.ToString() == ""throw new ArgumentException("参数错误!");
            List
<Employee> emplist = new List<Employee>();
            
for (int i = 1; i <= num; i++)
            
{
                Employee emp 
= new Employee() { EmployeeID = Guid.NewGuid(), CnName = i + "CnName", Sex = true, Age = i * 10, Email = i + "email@163.com", Birthday = new DateTime(19790202) };
                emplist.Add(emp);
            }

            
return emplist;
        }


        
private static void NotNull<T>(T o, string paramName) where T : class
        
{
            
if (o == nullthrow new ArgumentNullException(paramName);
        }

    }

}

主要就是这一句        [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Create")] 
意思就是说这个方法传递输入和输出参数都是Json形式,并且可以用后面加Create的形式来访问该方法,至于前面那个BodyStyle = WebMessageBodyStyle.Wrapped是什么意思留着下节详细说明

接下来修改Web.Config文件,其实只是是把<enableWebScript /> 替换为<webHttp/>代码如下(一部分)


<system.serviceModel>
        
<behaviors>
            
<endpointBehaviors>
                
<behavior name="ExtJSAndWCFChapter1.EmployeeServiceAspNetAjaxBehavior">
                    
<!--<enableWebScript />-->
                    
<webHttp/>
                
</behavior>
            
</endpointBehaviors>
        
</behaviors>
        
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
        
<services>
            
<service name="ExtJSAndWCFChapter1.EmployeeService">
                
<endpoint address="" behaviorConfiguration="ExtJSAndWCFChapter1.EmployeeServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="ExtJSAndWCFChapter1.EmployeeService"/>
            
</service>
        
</services>
    
</system.serviceModel>

现在可以编译并访问那个EmployeeService.svc文件,后面加上UriTemplate的值:例如http://localhost:1481/EmployeeService.svc/get。会得到“Method not allowed”的提示。如果访问出现错误,请确认修改的Web.Config是否正确。
接下来编写Default.aspx的代码:代码如下
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExtJSAndWCFChapter1._Default" %>

<!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 runat="server">
    
<title>Untitled Page</title>
    
<link rel="stylesheet" type="text/css" href="ExtJS/resources/css/ext-all.css" />
    
<!-- GC -->
    
<!-- LIBS -->

    
<script type="text/javascript" src="ExtJS/adapter/ext/ext-base.js"></script>

    
<script type="text/javascript" src="ExtJS/ext-all-debug.js"></script>
    
<script type="text/javascript" src="ExtJS/ext-all.js"></script>

    
<!-- ENDLIBS -->

    
<script type="text/javascript" language="javascript">
     Ext.onReady(function() 
{  
     
//设置Content-Type为application/json形式
     Ext.lib.Ajax.defaultPostHeader = 'application/json';
     
//访问失败的统一回调函数
     var onFailure = function(r, opts)
     
{
      Ext.
get("errors").insertHtml('afterend''<br/><br/>' + r.responseText, false);  
    }

    
//客户端创建一个实体
    var request={
    emp:
{     CnName:'xiaozhuang',
              Sex:
1,
              Age:
28,
              Birthday:
'/Date(62831853071)/',
              Email:
'Iamxiaozhuang@hotmail.com'
    }

    }

    Ext.Ajax.request(
{  
    url: 
'/EmployeeService.svc/Create',//要访问的方法地址
     method: 'POST'
     
params: Ext.util.JSON.encode(request), //把输入参数进行JSON编码
     success: function(response, options) { Ext.get('create-p').update(response.responseText);  }//输出方法返回结果
     failure: onFailure 
     }
);
     Ext.Ajax.request(

     url: 
'/EmployeeService.svc/Get'
     method: 
'POST'
     
params: Ext.util.JSON.encode(1),
     success: function(response, options) 
{ Ext.get('get-p').update(response.responseText); }
     failure: onFailure 
     }
);
     Ext.Ajax.request(

     url: 
'EmployeeService.svc/GetAll'
     method: 
'POST',  
     success: function(response, options) 
{ Ext.get('getall-p').update(response.responseText);}
     failure: onFailure 
     }
); 
     Ext.Ajax.request(

     url: 
'EmployeeService.svc/GetByNum'
     method: 
'POST',  
     
params: Ext.util.JSON.encode(8),
     success: function(response, options) 
{ Ext.get('GetByNum-p').update(response.responseText);}
     failure: onFailure 
     }
); 
     }
);
    
</script>
</head>
<body>
    
<form id="form1" runat="server">
     
<div>
        
<h3>
            Create:
</h3>
        
<p id="create-p">
        
</p>
        
<h3>
            Get:
</h3>
        
<p id="get-p">
        
</p>
        
<h3>
            GetAll:
</h3>
        
<p id="getall-p">
        
</p>
        
<h3>
            GetByNum:
</h3>
        
<p id="GetByNum-p">
        
</p>
        
<p id="errors">
        
</p>
    
</div>
    
</form>
</body>
</html>

最终的运行效果:

源代码下载在这里
 
posted @ 2007-12-07 18:14 小庄 阅读(7583) 评论(16)  编辑 收藏 网摘 所属分类: WCFAJAXExtJS

  回复  引用  查看    
#1楼2007-12-07 18:31 | Enzo      
最近都是ExtJS啊 o(∩_∩)o...
  回复  引用  查看    
#2楼2007-12-07 23:55 | CmSoft      
不错,支持:)
  回复  引用  查看    
#3楼2007-12-08 08:58 | t-mac.NET      
支持楼主,支持extjs
  回复  引用  查看    
#4楼2007-12-08 11:18 | xuqiang      
学习中...谢谢楼主,
  回复  引用  查看    
#5楼[楼主]2007-12-08 13:16 | 小庄      
@CmSoft
大家一起为园子里的EXTJS研究做点贡献吧,我想基于那个desktop的例子做一个ExtJS+WCF的系统框架出来,并测试一下在实际项目中的可行性,不过目前只研究了数据维护的部分,不知道以后还有没有时间,希望大家再接再厉

  回复  引用    
#6楼2007-12-08 13:52 | 乖乖同[未注册用户]
学习 ...LZ辛苦了....
  回复  引用  查看    
#7楼2007-12-08 14:04 | 行知      
不错,ExtJs使用WCF是一个很好的思路
  回复  引用    
#8楼2007-12-08 14:21 | 在线代理[未注册用户]
extjs有这么好吗,我yui都没有时间看,郁闷啊
  回复  引用    
#9楼2007-12-08 17:26 | ci[未注册用户]
不错。。。。
  回复  引用  查看    
#10楼2007-12-09 20:28 | Beginor      
WCF的返回数据的格式如果是JSON的话,必然要调用.Net3.5中的JSON序列化,众所周知,微软返回的JSON日期格式是特殊的,和其它的框架需要的格式是不同,而且和ExtJs也是不兼容的,如果需要日期格式的数据的话,那么你是怎样解决的?
  回复  引用  查看    
#11楼[楼主]2007-12-11 10:38 | 小庄      
@Beginor
请参看第二节 分页排序列表实现 中的paging.js文件,里面有个转换方法。

  回复  引用    
#12楼2008-05-26 15:46 | SimonGui[未注册用户]
您好:
请问一下,如果WCF的宿主程序是控制台程序,控制台程序支持TCP和HTTP的绑定。ExtJs如何调用WCF程序?IIS是宿主程序时,是否不支持nettcpbinding

  回复  引用  查看    
#13楼[楼主]2008-05-26 16:01 | 小庄      
ExtJs调用WCF的本质还是AJAX技术,所以不支持WCF的nettcpbinding,至于是否支持不宿主在IIS上的Httpbinding没有研究过,还有就是我的web.config里面是webHttpBinding,不是basichttpbinding或者mexhttpbinding。
  回复  引用    
#14楼2009-01-07 20:53 | gma[未注册用户]
你好,
请问为什么我的日期不能在页面中显示呢?
这是我的服务端: asp.net 不是WCF
---------------------------------------------
public partial class dateDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer jss = new JavaScriptSerializer();

List<Demo> list = new List<Demo>();

Demoitem = new Demo();
item.id = 1;
item.dt = DateTime.Now;
item.dtx = "7/1/2009";
list.Add(item);

item = new Demo();
item.id = 2;
item.dtx = "7/1/2009";
item.dt = DateTime.Now.AddMinutes(3);

list.Add(item);


string str =jss.Serialize(list);
Response.Clear();
Response.Write(str);
Response.End();

}
}
class Demo
{
public int id;
public DateTime dt;
public string dtx;
}

----------------------------------
JS如下:
-----------------------------------

Ext.BLANK_IMAGE_URL = './ext/resources/images/default/s.gif';
Ext.ns('CheckBoxDemo');

// application main entry point
Ext.onReady(function() {

Ext.QuickTips.init();

var prox = new Ext.data.HttpProxy({ url: 'dateDemo.aspx' });

//create Reader
var reader = new Ext.data.JsonReader({},[
{name:'id',maping:'id'},
{name:'dt',maping:'dt'}
,{name:'dtx',maping:'dtx',type: 'date'}

]);





//create Store
var store = new Ext.data.Store({
proxy:prox,
reader:reader
});

function formatDate(value){
alert(value);
return value ? value.dateFormat('Y m d') : '';
};
//create Grid
var cm = new Ext.grid.ColumnModel([
{id:'id',
header:'编号',
dataIndex:'id',
width:80,
sortable: true,
editor: new Ext.form.TextField({ allowBlank: false, blankText: '该字段不能为空' })
},
{header:'dt',dataIndex:'dt',width:280,sortable:true,renderer: formatDate,
editor: new Ext.form.DateField({format: 'Y m d' })
},
{header:'dtx',dataIndex:'dtx',width:280,sortable:true,renderer: formatDate,
editor: new Ext.form.DateField({format: 'Y m d'})
}

]);

var grid = new Ext.grid.EditorGridPanel({
//store
store:store,
cm:cm,
renderTo:'grid_checkbox',
width:800,
height:600,
title: '编辑JOBS表',
frame: true,
clicksToEdit: 2,

tbar:[{
text:'AddItem',
handler:function (){
var count = store.getModifiedRecords();
var str="";
for(var i=0;i<count.length;i++)
{
str +=count[i].json.Job_Id+"&nbsp;&nbsp;"
str+=count[i].json.Min_lvl+"&nbsp;&nbsp;";
str+=count[i].get("Min_lvl")+"<br>";

}

Ext.MessageBox.alert('hahah',str,Ext.emptyFn,this);
}
}]

});

store.load();






}); // eo function onReady

Ext.grid.CheckColumn = function(config){
Ext.apply(this, config);
if(!this.id){
this.id = Ext.id();
}
this.renderer = this.renderer.createDelegate(this);
};

Ext.grid.CheckColumn.prototype ={
init : function(grid){
this.grid = grid;
this.grid.on('render', function(){
var view = this.grid.getView();
view.mainBody.on('mousedown', this.onMouseDown, this);
}, this);
},

onMouseDown : function(e, t){
if(t.className && t.className.indexOf('x-grid3-cc-'+this.id) != -1){
e.stopEvent();
var index = this.grid.getView().findRowIndex(t);
var record = this.grid.store.getAt(index);
record.set(this.dataIndex, !record.data[this.dataIndex]);
}
},

renderer : function(v, p, record){
p.css += ' x-grid3-check-col-td';
return '<div class="x-grid3-check-col'+(v?'-on':'')+' x-grid3-cc-'+this.id+'">&#160;</div>';
}
};


在编辑状态下无法显示日期





  回复  引用    
#15楼2009-03-03 19:32 | xiaocai[未注册用户]
您好,谢谢您的分享,但是我现在出了一个问题,按照你方法定义的WCF,怎样远程调用呢?我老是失败。郁闷死了。
  回复  引用  查看    
#16楼[楼主]2009-03-04 09:06 | 小庄      
@xiaocai
你有没试下给WCF加个跨域文件?




发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 987092




相关文章:

相关链接: