Search Flex Components Free

Custom Search

January 1, 2008

Flex and .NET web services

Code Example

Seen a few requests for .NET web service and Flex examples, here is a quick example.

First create a web service function (my code is in VB.NET but you get the idea).

<WebMethod()> _
Public Function SayHello(ByVal strMessage As String) As String
Return "Hello " & strMessage
End Function

This amazingly complex bit of code echo's out it's arguement with the string "Hello" attached.

Now we will rig to Flex using the following code.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=" http://www.macromedia.com/2003/mxml " width="600" height="450">
<mx:WebService id="EchoStuff" wsdl=" http://localhost/EchoService/Echo.asmx?WSDL " showBusyCursor="true" fault="alert(event.fault.faultstring)">
<mx:operation name="SayHello">
<mx:request>
<strMessage>{name.text}</strMessage>
</mx:request>
</mx:operation>
</mx:WebService>
<mx:VBox>
<mx:TextInput id="name"></mx:TextInput>
<mx:Button click="EchoStuff.SayHello.send()"></mx:Button>
<mx:Label text="{EchoStuff.SayHello.result}"></mx:Label>
</mx:VBox>
</mx:Application>

Here we we will use a textbox (Flex calls them textinput) and on the button click event send it's contents to the web service. A label will then display the contents back. A few notes here.

Web services are called using the following.

<mx:WebService id="EchoStuff" wsdl=" http://localhost/EchoService/Echo.asmx?WSDL " showBusyCursor="true" fault="alert(event.fault.faultstring)">
<mx:operation name="SayHello">
<mx:request>
<strMessage>{name.text}</strMessage>
</mx:request>
</mx:operation>
</mx:WebService>

Note that the we specify the location to the WSDL for our webservice. We then map mx:operation to the method name of our web service. To send a request to the web service we use mx:request and within that the parameter name and what data we will send (in this case the textinput contents). To trigger the web service we use

EchoStuff.SayHello.send()">

which is tied to the button click event (it must have an event in order to trigger). The result can then be obtained using

EchoStuff.SayHello.result

Note that everything is case senstive so watch how you declare and make use of things within Flex. One of the interesting things I found was that if you get the case wrong when using mx:operation some odd things start happening. For example if you use.

<mx:operation name="Sayhello">

The web service method fires but the mx:request is not passed.

Related Flex Tutorials