Flex调用WebService进行数据查询和显示(调整)
在这里向大家介绍一下Flex通过调用.net WebService进行数据查询和显示的实现。对于Flex的介绍就不描述,有兴趣的朋友可以到Adobe的官方站了解(http://www.adobe.com/devnet/flex/)。Flex提供了Remoting,HttpService,WebService等对象进行网络数据交互。在本文所用到的对象是WebService,它提供了方便灵活的WebService方法调用。
先看本文例子的效果图:
建立基于NorthWind.Employees表的数据查询方法。
public string ListEmployees()//获取所有雇员返回相关的XML格式字符串
<Employees>
<Item>
<EmployeeID>1</EmployeeID>
<EmployeeName>NancyDavolio</EmployeeName>
<Title>Sales Representative</Title>
</Item>
<Item>
<EmployeeID>2</EmployeeID>
<EmployeeName>AndrewFuller</EmployeeName>
<Title>Vice President, Sales</Title>
</Item>
</Employees>
public string GetEmployee(int employeeid)//获取指定索引雇员信息的XML格式字符串
<Body>
<Item>
<EmployeeID>1</EmployeeID>
<FirstName>Nancy</FirstName>
<LastName>Davolio</LastName>
<Title>Sales Representative</Title>
<TitleOfCourtesy>Ms.</TitleOfCourtesy>
<BirthDate>1948-12-8 0:
<HireDate>1992-5-1 0:
<Address>507 - 20th Ave. E. Apt. 2A</Address>
<City>
<Region>
<PostalCode>98122</PostalCode>
<Country>
<Notes></Notes>
</Item>
<Error>
</Error>
</Body>
在这里可能有人问为什么不直接返回可以序列化的对象,这样不是更方便吗?刚开始时我想直接返回DataSet但是Flex并不支持会产生调用错误(具体情况还在查找中)。虽然返回的是XML的字符串,但Flex提供灵活的XML文本处理对象直接支持XML文件转换成对象操作(这功能很喜欢,不知道C#3.0是否提供)。
在Flex中定义WebService访问对象:
<mx:WebService id="WS" wsdl="http://localhost/WebService2/Service1.asmx?WSDL"
fault="Alert.show(event.fault.faultString), 'Error'">
<mx:operation name="ListEmployees" resultFormat="object" result="EmployeeList(event)">
</mx:operation>
<mx:operation name="GetEmployee" resultFormat="object" result="GetObj(event)">
<mx:request>
<employeeid>{employeeList.selectedItem.EmployeeID}</employeeid>
</mx:request>
</mx:operation>
</mx:WebService>
operation是描述相关方法。
result 是方法调用完成后的委托方法。
request 是描述相关方法的参数,通过{employeeList.selectedItem.EmployeeID}把参数值指定到相关对象的属性上。
可以通过WS.GetEmployee()来进行相关方法的调用。
调用GetEmployee方法后的处理代码:
function EmployeeList(event:ResultEvent):void
{
var doc:XMLDocument = new XMLDocument(event.result.toString());
var obj:XML;
var employees:Array = new Array();
for(var i:int=0;i<doc.firstChild.childNodes.length;i++)
{
obj = new XML(doc.firstChild.childNodes[i].toString());//创建一个XML对象,直接支持对象属性访问。
employees.push(obj);
}
employeeList.dataProvider=employees;//把数据源绑定到列表中
}
调用GetObj方法后处理的代码:
function GetObj(event:ResultEvent)
{
var re:XML = new XML(event.result.toString());
if(re.Error != null && re.Error !="")
{
Alert.show(re.Error);
return;
}
editAddress.text= re.Item.Address;
editBirthDate.text = re.Item.BirthDate;
editCity.text = re.Item.City;
editCountry.text = re.Item.Country;
editEmployeeID.text = re.Item.EmployeeID;
editFirstName.text = re.Item.FirstName;
editLastName.text = re.Item.LastName;
editNotes.text = re.Item.Notes;
editPostalCode.text = re.Item.PostalCode;
editRegion.text = re.Item.Region;
editTitle.text = re.Item.Title;
editTitleOfCourtesy.text = re.Item.TitleOfCourtesy;
editHireDate.text = re.Item.HireDate;
}
从上面的代码可以看到XML是一个非常灵活的对象,它可以把XML格式的字符串转成相关对象进行操作。
一个简单的调用WebServie方法进行数据查询和显示就完成了,看上去是不是很简单方便。不过Flex是基于Flash的Activex表现的,本质上和传统的JavaScript结合Html有很大差别。
对于WebService的实现代码就不详细讲了,相信大家在VS.NET下写WebService已经熟悉了。
下载相关代码
调整
定发现Flex在数据绑定这方面做得很好,正如沐枫所说 所有数据通过属性绑定就能完成工作。
.NET WebService返回的对象,Flex也能够很好地支持并不需要做特别的修改。
以下调整MXML文件后的代码:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application initialize="OnInit()" xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" cornerRadius="20" borderColor="#8080ff" viewSourceURL="srcview/index.html">
<mx:Form width="100%" height="61" id="panel1">
<mx:PopUpButton width="254" id="selectemp"/>
<mx:DataGrid id="employeeList" width="397" change="ItemSelected()"
dataProvider="{WS.ListEmployees.lastResult}" >
<mx:columns>
<mx:DataGridColumn visible="false" headerText="EmployeeID" dataField="EmployeeID"/>
<mx:DataGridColumn headerText="EmployeeName" dataField="EmployeeName"/>
<mx:DataGridColumn headerText="Title" dataField="Title"/>
</mx:columns>
</mx:DataGrid>
<mx:FormItem fontFamily="Times New Roman" width="249">
</mx:FormItem>
</mx:Form>
<mx:Form width="100%" height="407" id="panel2">
<mx:FormItem label="EmployeeID" width="252">
<mx:TextInput width="157" id="editEmployeeID"
text="{WS.GetEmployee.lastResult.EmployeeID}"/>
</mx:FormItem>
<mx:FormItem label="FirstName" width="252">
<mx:TextInput width="160" id="editFirstName"
text="{WS.GetEmployee.lastResult.FirstName}"/>
</mx:FormItem>
<mx:FormItem label="LastName" width="252">
<mx:TextInput width="162" id="editLastName"
text="{WS.GetEmployee.lastResult.LastName}"/>
</mx:FormItem>
<mx:FormItem label="Title" width="253">
<mx:TextInput id="editTitle"
text="{WS.GetEmployee.lastResult.Title}"/>
</mx:FormItem>
<mx:FormItem label="TitleOfCourtesy" width="254">
<mx:TextInput id="editTitleOfCourtesy"
text="{WS.GetEmployee.lastResult.TitleOfCourtesy}"/>
</mx:FormItem>
<mx:FormItem label="BirthDate">
<mx:DateField width="106" id="editBirthDate"
text="{WS.GetEmployee.lastResult.editBirthDate}" />
</mx:FormItem>
<mx:FormItem label="HireDate">
<mx:DateField width="107" id="editHireDate"
text="{WS.GetEmployee.lastResult.HireDate}"/>
</mx:FormItem>
<mx:FormItem label="Address" width="469">
<mx:TextInput width="364" id="editAddress"
text="{WS.GetEmployee.lastResult.Address}"/>
</mx:FormItem>
<mx:FormItem label="City">
<mx:TextInput id="editCity"
text="{WS.GetEmployee.lastResult.City}"/>
</mx:FormItem>
<mx:FormItem label="Region">
<mx:TextInput id="editRegion"
text="{WS.GetEmployee.lastResult.Region}"/>
</mx:FormItem>
<mx:FormItem label="PostalCode">
<mx:TextInput id="editPostalCode"
text="{WS.GetEmployee.lastResult.PostalCode}"/>
</mx:FormItem>
<mx:FormItem label="Country">
<mx:TextInput id="editCountry"
text="{WS.GetEmployee.lastResult.Country}"/>
</mx:FormItem>
<mx:FormItem label="Notes">
<mx:PopUpButton label="..." id="editRemarkView"/>
</mx:FormItem>
<mx:TextArea width="355" height="64" id="editNotes"
text="{WS.GetEmployee.lastResult.Notes}"/>
</mx:Form>
<mx:Script>
<![CDATA[
import mx.messaging.messages.RemotingMessage;
import mx.rpc.events.ResultEvent;
import mx.rpc.soap.WebService;
import mx.rpc.events.FaultEvent;
import mx.rpc.Fault;
import mx.controls.Alert;
function OnInit():void
{
panel1.removeChild(employeeList);
selectemp.popUp=employeeList;
panel2.removeChild(editNotes);
editRemarkView.popUp = editNotes;
WS.ListEmployees();
}
function ItemSelected():void
{
selectemp.label=employeeList.selectedItem.EmployeeName;
WS.GetEmployee();
}
]]>
</mx:Script>
<mx:WebService id="WS" wsdl="http://localhost/WebService2/Service1.asmx?WSDL"
fault="Alert.show(event.fault.faultString), 'Error'">
<mx:operation name="ListEmployees" resultFormat="object" >
</mx:operation>
<mx:operation name="GetEmployee" resultFormat="object" >
<mx:request>
<employeeid>{employeeList.selectedItem.EmployeeID}</employeeid>
</mx:request>
</mx:operation>
</mx:WebService>
</mx:Application>
相关的WebService方法:
[WebMethod]
[System.Xml.Serialization.XmlInclude(typeof(EmployeeItem))]
public ArrayList ListEmployees()
{
SqlCommand cmd = new SqlCommand("select * from employees");
ArrayList list = new ArrayList();
using(SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
cmd.Connection = conn;
using(IDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
EmployeeItem item = new EmployeeItem();
item.EmployeeID = reader["EmployeeID"].ToString();
item.EmployeeName = reader["FirstName"].ToString()+reader["LastName"];
item.Title = reader["Title"].ToString();
list.Add(item);
}
}
}
return list;
}
[WebMethod]
public ItemInfo GetEmployee(int employeeid)
{
ItemInfo info = new ItemInfo();
SqlCommand cmd = new SqlCommand("select * from employees where employeeid=" +employeeid);
using(SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
cmd.Connection = conn;
using(IDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
{
info.EmployeeID =reader["EmployeeID"].ToString();
info.FirstName =reader["FirstName"].ToString();
info.LastName =reader["LastName"].ToString();
info.Title =reader["Title"].ToString();
info.TitleOfCourtesy =reader["TitleOfCourtesy"].ToString();
info.BirthDate =(DateTime)reader["BirthDate"];
info.HireDate =(DateTime)reader["HireDate"];
info.Address =reader["Address"].ToString();
info.City =reader["City"].ToString();
info.Region=reader["Region"].ToString();
info.PostalCode =reader["PostalCode"].ToString();
info.Country =reader["Country"].ToString();
info.Notes =reader["Notes"].ToString();
}
}
}
return info;
}