ExtJs是一套非常不错的javascript UI库(第一次接触ExtJs的,可到官方网站http://www.extjs.com/deploy/dev/examples/samples.html看下示例。相信不少人会心动的),不仅组件丰富,效果漂亮,而且ExtJs集成的Ajax功能可以方便的与.Net的WCF进行交互.
这里我们将演示ExtJs的FormPanel从WCF加载数据,以及如何提交数据到WCF服务端
1.首先来定义一个用于传输信息的Class(实际开发中,可以是Linq to Sql的Class或任何可序列化的实体类)
[DataContract]
public class MyData
{
[DataMember]
public string id;
[DataMember]
public string text;
}
非常简单,MyData中仅定义了二个成员id,text,加上[DataContract]与[DataMember]表明该类可以序列化
2.再定义几个用于跟ExtJs交互的方法(初次接触Ajax与WCF交互的同志,建议参考一下老张的"Ajax与WCF交互-WCF之美(http://www.cnblogs.com/jillzhang/archive/2008/06/13/1219201.html)")
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService
{
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, Method = "*", UriTemplate = "GetMyData")]
public MyData GetMyData()
{
System.Threading.Thread.Sleep(1000);
MyData _Node = new MyData() { id = "1", text = "test text" };
return _Node;
}
/**//// <summary>
/// RESTFul WCF用于Get方式取得ExtJs提交的数据(Json)
/// </summary>
/// <param name="id"></param>
/// <param name="text"></param>
/// <returns></returns>
[OperationContract]
[WebInvoke(Method = "*", ResponseFormat = WebMessageFormat.Json, UriTemplate = "SaveMyData?id={id}&text={text}")]
public MyData SaveMyData(string id,string text)
{
System.Threading.Thread.Sleep(1000);
MyData _Node = new MyData() { id = id, text = text };
return _Node;
}
/**//// <summary>
/// Post方法处理ExtJs提交的数据(Json格式)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[OperationContract]
[WebInvoke(Method = "*", ResponseFormat = WebMessageFormat.Json, UriTemplate = "SaveMyData2")]
public MyData SaveMyData2(Stream input)
{
string s = "";
using (StreamReader sr = new StreamReader(input))
{
s = sr.ReadToEnd();
}
NameValueCollection qs = HttpUtility.ParseQueryString(s);
string id = qs["id"];
string text = qs["text"];
System.Threading.Thread.Sleep(1000);
MyData _Node = new MyData() { id = id, text = text };
return _Node;
}
}