Click here to Skip to main content
15,115,667 members
Articles / Web Development / ASP.NET
Posted 26 Jun 2009


42 bookmarked

Flex Communication with ASP.NET WebService

Rate me:
Please Sign up or sign in to vote.
4.80/5 (19 votes)
26 Jun 2009CPOL4 min read
This article explains how to use an ASP.NET WebService from Adobe Flex
Image 1


In this article, I tried to explain how to use an ordinary ASP.NET WebService to use with Adobe Flex. I used the flex tag <mx:WebService> to make this work. Basic knowledge in Flex is important to understand this article.

Remember that WebService is just an option. There are many other options like HTTPService, Flex Remoting, etc.


I would like to point you to my earlier CodeProject article Flex HTTPService with ASP.NET where I demonstrated the use of flex tag <mx:HTTPService> to interact with an ordinary ASP.NET application.

Development Tools I Used

  • C# on Visual Studio 2008 with .NET Framework 3.5
  • Adobe Flex Builder 3.0
  • SQL Server 2008 sample database

What Attached Source Code Does

  • ASP.NET WebService has two methods:
    • GetEmployees() - To get records from webservice
    • SaveEmployee() - To save records to database via webservice
  • Flex MXML file:
    • A DataGrid - To show records from WebService
    • A data entry box - To save records to database via WebService

What I Expect You to Get from this Article

  • How to do database operations with Flex and ASP.NET
  • How to interact with an ASP.NET WebService from Flex
    • How to get data from a WebService
    • How to send data to a WebService
    • How to send parameters when calling a webservice method

What to Remember When you Create an ASP.NET Webservice to Use with Flex?

  • Nothing. You just create an ordinary ASP.NET WebService just like you did in the past.

Using the Code


For demonstration purposes, I created a sample database test and a sample table tblEmployee with the below schema. You will need this if you try to execute the attached sample.

CREATE TABLE [dbo].[tblEmployee](

[EmpId] [nchar](50) NULL,

[EmpName] [nchar](50) NULL,

[EmpEmail] [nchar](50) NULL

) ON [PRIMARY]       

ASP.NET WebService

As I said, the WebService is just an ordinary ASP.NET WebService project with just two Web methods, one for getting records from database and the other one to save a new record.

Warning: Note that I created these files just for demonstration purposes and did not follow any standards either in ASP.NET WebService or Flex MXML file.

public class Service : WebService
    SqlConnection con = new SqlConnection
	("Data Source=localhost;Initial Catalog=test;User id=;Password=");

    // Method to get all records from database
    public List<Employee> GetEmployees()
        // Method does not follow any coding standards. This is just for demo purposes.
        var emplist = new List<Employee>();
        Employee emp;
        var da = new SqlDataAdapter("SELECT EmpId, 
		EmpName, EmpEmail from tblEmployee", con);
        var dt = new DataTable();
        foreach (DataRow dr in dt.Rows)
            emp = new Employee
                          EmpId = dr["EmpId"].ToString(),
                          EmpName = dr["EmpName"].ToString(),
                          EmpEmail = dr["EmpEmail"].ToString()
        return emplist;
    // Method to save a record
    public void SaveEmployee(string empId, string empName, string empEmail)
        // Method does not follow any coding standards. This is just for demo purposes.
        var cmd = new SqlCommand("INSERT INTO tblEmployee 
	(EmpId, EmpName, EmpEmail) VALUES(@empid, @empname, @empemail)",con);
        cmd.Parameters.Add(new SqlParameter("@empid", empId));
        cmd.Parameters.Add(new SqlParameter("@empname", empName));
        cmd.Parameters.Add(new SqlParameter("@empemail", empEmail));

// Employee Class
public class Employee
    public string EmpId = string.Empty;
    public string EmpName = string.Empty;
    public string EmpEmail = string.Empty;


First, you need to add <mx:WebService> tag to your Flex application mxml file. Here is what I have now:

<mx:WebService id="ws" wsdl="http://localhost/TestWebService/Service.asmx?WSDL" 

Note the call of webservice with URL: http://localhost/TestWebService/Service.asmx?WSDL.

You can see that I defined two operations:

  1. GetEmployees and 
  2. SaveEmployee

which are defined in our ASP.NET WebService as well. When you invoke the required webservice call, the corresponding result event handler works and you will get the data sent by WebService in that attached event method. Here the attached event handler methods are GetEmployees(event) and SaveEmployee(event).

Remember that you can call a webservice dynamically also without using these tags. Also there are asynchronous token methods which I believe are out of scope of this article.

Next I added a DataGrid to show the records we get from WebService. Also I used a Form to do data entry for adding new records.

<mx:Panel>, <mx:HBox> etc. are used to get a good appearance for the application. These have nothing to do with our webservice calls.

How Stuff Works

In the <mx:Applicaiton> tag, I used creationComplete="init()" so that init()method will be called when the Flex application is loaded. Inside the init(), I called our webservice method ws.GetEmployees().

Once the ws.GetEmployees() method is called, the attached result handler gets invoked if the call is a success. Keep in mind, there is a common fault handler attached which will get triggered when there is an error associated with webservice.

The attached result handler of ws.GetEmployees() is:

private function GetEmployees(event:ResultEvent):void {
// Databind data from webservice to datagrid
datagrid.dataProvider = event.result; 

In this method, we bind the incoming data to our datagrid to show records.

Next is how we save records. I used three <mx:TextInput> boxes and one <mx:Button> for the data entry of a new record. An event handler AddRecord(event) is attached which triggers the click event.

<mx:Form x="608" y="74" width="100%" height="100%" borderStyle="solid">
<mx:FormItem label="EmpId">
<mx:TextInput width="106" id="txtEmpId"/>
<mx:FormItem label="EmpName">
<mx:TextInput width="106" id="txtEmpName"/>
<mx:FormItem label="EmpEmail">
<mx:TextInput width="106" id="txtEmpEmail"/>

<mx:FormItem width="156" horizontalAlign="right">
<mx:Button label="Add" id="btnAdd" click="AddRecord(event)"/>

When the user clicks this button, the corresponding method will be triggered.

private function AddRecord(event:MouseEvent):void {
// Save a record using a WebService method
ws.SaveEmployee(txtEmpId.text, txtEmpName.text, txtEmpEmail.text); // 

This method calls the WebService method ws.SaveEmployee() with the parameters which we get from the data entry form. As we know, again the result handler of this WebService method will be triggered which is:

private function SaveEmployee(event:ResultEvent):void {
// To Refresh DataGrid;
ws.GetEmployees();"Saved Successfully");

In this event, we call the WebService ws.GetEmployees() again to refresh the DataGrid so that it displays new record also. Since there is an call, you will be notified instantly "Saved Successfully" once the data is saved.


  • 26th June, 2009: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Praveen Nair (NinethSense)
India India
Praveen.V.Nair - aka NinethSense - PMP, Microsoft MVP - is working as a Head of Technology and Architecture at Orion India Systems, Kochi, India. He has been playing with electronics from the age of 10 and with computers from the age of 14. He usually blogs at

Comments and Discussions

QuestionI tried to pass an integer from to flex, but always got value of 0 Pin
ladyleaf5-Jan-15 19:57
Memberladyleaf5-Jan-15 19:57 
GeneralMy vote of 5 Pin
shanawazway23-May-12 2:20
Membershanawazway23-May-12 2:20 
GeneralMy vote of 5 Pin
Webgur13-Sep-11 2:50
MemberWebgur13-Sep-11 2:50 
GeneralHai Friends!!!! beginners just try this link Pin
vijay_vignesh11-Jan-11 3:15
Membervijay_vignesh11-Jan-11 3:15 
GeneralReturning a single instance of Employee Pin
NeCroFire2-Jul-10 4:23
MemberNeCroFire2-Jul-10 4:23 
Generali can run your code but not inserting the data. Pin
kakadiya20-May-10 23:32
Memberkakadiya20-May-10 23:32 
GeneralRe: i can run your code but not inserting the data. Pin
Praveen Nair (NinethSense)21-May-10 0:14
MemberPraveen Nair (NinethSense)21-May-10 0:14 
GeneralRe: i can run your code but not inserting the data. Pin
kakadiya21-May-10 0:24
Memberkakadiya21-May-10 0:24 
GeneralRe: i can run your code but not inserting the data. Pin
kakadiya21-May-10 1:17
Memberkakadiya21-May-10 1:17 
GeneralRe: i can run your code but not inserting the data. Pin
Praveen Nair (NinethSense)21-May-10 2:15
MemberPraveen Nair (NinethSense)21-May-10 2:15 
Generalawesome !!!!!!!!!! Pin
lxjhonson19-Feb-10 2:32
Memberlxjhonson19-Feb-10 2:32 
SafetyManNew22-Jan-10 19:48
MemberSafetyManNew22-Jan-10 19:48 
GeneralVery nice (Exactly what I needed to get me started in Flex): how to ADD PARAMENTERS AND ARGUMENTS WITH THE WEB SERVICE use mx:request and xml encode each parameter [modified] Pin
SafetyManNew20-Jan-10 10:09
MemberSafetyManNew20-Jan-10 10:09 
GeneralMy vote of 2 Pin
cppwizard4-Jan-10 19:36
Membercppwizard4-Jan-10 19:36 
GeneralRe: My vote of 2 Pin
Praveen Nair (NinethSense)20-Jan-10 18:37
MemberPraveen Nair (NinethSense)20-Jan-10 18:37 
QuestionUnable to load WSDL [modified] Pin
Alex Dove12-Nov-09 11:36
professionalAlex Dove12-Nov-09 11:36 
AnswerRe: Unable to load WSDL Pin
klangued9-Dec-09 9:49
Memberklangued9-Dec-09 9:49 
GeneralSecurity error accessing url when running the flex app Pin
corefour3-Nov-09 12:06
Membercorefour3-Nov-09 12:06 
GeneralRe: Security error accessing url when running the flex app Pin
klangued9-Dec-09 9:47
Memberklangued9-Dec-09 9:47 
GeneralRe: Security error accessing url when running the flex app Pin
corefour11-Dec-09 11:36
Membercorefour11-Dec-09 11:36 
Generalnice article Pin
Krish anghan8-Jul-09 4:29
MemberKrish anghan8-Jul-09 4:29 
GeneralRe: nice article Pin
Praveen Nair (NinethSense)8-Jul-09 4:41
MemberPraveen Nair (NinethSense)8-Jul-09 4:41 
GeneralDid u get any reply from suthor? Pin
kakadiya20-May-10 23:59
Memberkakadiya20-May-10 23:59 
GeneralNice one ! Pin
Abhijit Jana6-Jul-09 10:11
professionalAbhijit Jana6-Jul-09 10:11 
GeneralRe: Nice one ! Pin
Praveen Nair (NinethSense)6-Jul-09 20:02
MemberPraveen Nair (NinethSense)6-Jul-09 20:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.