ExtJS 和 .NET Web Services






4.83/5 (15投票s)
如何在 ExtJS 中使用 .NET Web Services
引言
ExtJS 是一个非常强大的 JavaScript 库,非常适合在 Web 浏览器中创建丰富的图形用户界面。 您可以使用它构建各种用途的应用程序,并使用 XML、JSON 或您自己的交换格式集成来自许多来源和技术的数据。 另一方面,.NET 提供了强大的服务器端功能,例如 Entity Framework、LINQ 和许多强大的类。 在本文中,我想向您展示如何以最便捷的方式集成这两种技术,并利用它们各自的优势。
解决方案
当您尝试访问不同服务器上的不同数据源时,当今世界最好的方法是使用 Web Services。 这样,您可以使用不同的技术构建可供许多供应商访问的 SOA 解决方案。 当我们决定使用 ExtJS 作为 GUI 部分,ASP.NET 作为服务器部分时,直接使用 ASP.NET Web Services 是理想的选择。 ExtJS 本身并不原生支持 SOAP XML 数据源。 如果您愿意,可以编写自己的数据代理,但我会向您展示这并非必要。 从版本 2.0 开始,ASP.NET Web Services 允许您使用 JSON 格式而不是 SOAP XML 进行通信。
与大多数情况一样,当您想要配置 .NET 类的行为时,可以使用属性。 在这里,我们需要使用 ScriptService
属性(来自 System.Web.Script.Services
命名空间)装饰 Web Service 类,然后使用 ScriptMethod
属性装饰方法。 类属性不需要任何配置,但我们需要为方法装饰器添加一些配置。 我们需要指定的是方法响应格式,在本例中为 ResponseFormat=ResponseFormat.Json
,并允许它使用 GET HTTP 方法与 Web Service 方法通信。 这就是我们在服务器端需要做的全部。 那么现在我们进入 GUI 部分。
// Entity class declaration
public class Agent {
private int _agentID;
public int AgentID { get { return _agentID; } set { _agentID = value; } }
private string _firstName;
public string FirstName { get { return _firstName; } set { _firstName= value; } }
private string _lastName;
public string LastName { get { return _lastName; } set { _lastName= value; } }
public Agent() {}
public Agent(int agentID, string firstName, string lastName) {
_agentID = agentID;
_firstName= firstName;
_lastName= lastName;
}
}
...
// WebService declaration
[ScriptService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json,
UseHttpGet = true, XmlSerializeString = false)]
public List<Agent> GetAgents() {
List<Agent> agents = new List<Agent>();
agents.Add( new Agent('1', 'Jelena', 'Akerhus') );
agents.Add( new Agent('2', 'Londo', 'Molari') );
return agents;
}
}
这个 Web Service 将生成如下数据结构
{ "d": [{"AgentID": 1, "FirstName": "Jelena",
"LastName": "Akerhus"},{"AgentID": 2,
"FirstName": "Londo", "LastName": "Molari"}]}
我们可以使用 ExtJS 中的一个 JSON 启用的数据存储区,称为 Ext.data.JsonStore
来访问此数据
// Create store
var myStore = new Ext.data.JsonStore({
// Load data at once
autoLoad: true,
// Override default http proxy settings
proxy: new Ext.data.HttpProxy({
// Call web service method using GET syntax
url: 'Service.asmx/GetAgents',
// Ask for Json response
headers: {'Content-type': 'application/json'}
}),
// Root variable
root: 'd',
// Record identifier
id: 'AgentID',
// Fields declaration
fields: ['AgentID', 'FirstName', 'LastName']
});
并使用数据网格显示获得的信息
var grid = new Ext.grid.GridPanel({
// Set store
store: myStore,
// Columns definition
columns: [
{ dataIndex: 'AgentID' },
{ dataIndex: 'FirstName' },
{ dataIndex: 'LastName' }
],
// Render grid to dom element with id set to panel
renderTo: 'panel'
});
在这种情况下,我们从 ASP.NET Web Service 获取数据,并在 ExtJS 数据网格中显示它。 这种方法有一个很大的缺点:Web Service 必须位于同一域内。 在下一篇文章中,我将向您展示如何以简单的步骤从 ExtJS 调用跨域 ASP.NET Web Service。
历史
- 2009 年 5 月 6 日:初始发布
- 2009 年 6 月 19 日:添加了项目和源代码