AJAX with ASP.NET using Visual Studio 2005 and AJAX Toolkit
Written by Deepesh
The following article shows how to AJAX power your web application using the ever popular ASP.NET platform using Visual Studio and AJAX Toolkit. Learn how to improve performance and add new features using AJAX with ASP.NET
Asynchronous JavaScript And XML or a more popular word common to all developers AJAX, is becoming a powerful tool for web development. AJAX makes web pages more interactive by reducing the no. of page refreshes and postbacks. Although AJAX is a client side technique most of its execution depends upon server side processing.
AJAX is basically based on JavaScript and HTTP requests. It had been there since long but its presence was made felt by Google. Before AJAX came into being there had been other techniques one of then include using dummy frames which were hidden to the user, these hidden frames were used to handle the postbacks. For development of web applications with AJAX Microsoft has developed an AJAX toolkit which can be downloaded from http://ajax.asp.net.
In this article we are going to create a page that contains a web service which SELECTS, UPDATES, DELETES AND INSERTS employee data using Visual C#.
Requirements
Visual Studio 2005 (with AJAX Toolkit Installed)
SQL Server with Northwind Database
Creating The Web Site
Open Visual Studio 2005.
Create a new website and notice that the installation of AJAX toolkit adds "ASP.NET AJAX Enabled Web Site" template.
1.) Create an AJAX Enabled Web Site.
The difference between the two, i.e., ASP.NET Website and AJAX enabled website is basically in the web.config file. In ajax enabled website the web.config refers to System.Web.Extensions.
2.) Now Create a new web service in your website and name it EmployeeService.asmx.
This Service wil containt 5 methods.
+ GetEmployees() - Returns a list of employees from the Employees table.
+ GetEmployee() - Accepts an EmployeeID and returns its details as an Employee object.
+ Insert(), Update(), Delete()
The GetEmployees() and GetEmployee method return data in form of objects of type Employee whose class definition is given in the next step.
3.) Right click on the App_code folder and select add new item and add a new class called Employee.
The code inside the class employee is given under.
public class Employee
{
private int intEmployeeID;
private string strFirstName;
private string strLastName;
public int EmployeeID
{
get
{
return intEmployeeID;
}
set
{
intEmployeeID = value;
}
}
public string FirstName
{
get
{
return strFirstName;
}
set
{
strFirstName = value;
}
}
public string LastName
{
get
{
return strLastName;
}
set
{
strLastName = value;
}
}
}
The Employee class defines three variables for storing the EmployeeID, Firstname and Lastnme of employee.
4.)Open the web.config file and add a <connectionStrings> section as follows:
This stores a database connection string that points to the Northwind database. Make sure to change SQL Server name/IP and authentication details to match your environment.
5.) Now Open EmployeeService.cs and add the following code.
This code uses the ConfigurationManager Class to read the connection string from web.config file to connect to Northwind database.
6.) Add the web method as follows
[WebMethod] public Employee[] GetEmployees()
{
SqlConnection cnn = new SqlConnection(strConn);
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "select employeeid,firstname, lastname from employees";
SqlDataReader reader = cmd.ExecuteReader();
List<Employee> list = new List<Employee>();
while (reader.Read())
{
Employee emp = new Employee();
emp.EmployeeID = reader.GetInt32(0);
emp.FirstName = reader.GetString(1);
emp.LastName = reader.GetString(2);
list.Add(emp);
}
reader.Close();
cnn.Close();
return list.ToArray();
}
This code creates a SqlConnection and SqlCommand object. It then executes a SELECT query to read the EmployeeID, Firstname and Lastname from the Employees table. The results are read bya na SqlDataSource instance. Then, a generic List of Employee objects is created. A while loop iterates through the SqlDataReader. With each iteration, a new Employee object is created and its EmployeeID, FirstName, and LastName properties are set. The Employee object then is added to the List. After the while loop completes, SqlDataReader and SqlConnection are closed.
The return type of the GetEmployees() web method being an array of Employee objects. Hence, the List is converted into Employee array using the ToArray() method of the List class.
7.) Next add the following methods
[WebMethod] public Employee GetEmployee(int pEmployeeId)
{
SqlConnection cnn = new SqlConnection(strConn);
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "select employeeid,firstname,lastname from employees where employeeid=@id";
SqlParameter id = new SqlParameter("@id", pEmployeeId);
cmd.Parameters.Add(id);
SqlDataReader reader = cmd.ExecuteReader();
Employee emp = new Employee();
while (reader.Read())
{
emp.EmployeeID = reader.GetInt32(0);
emp.FirstName = reader.GetString(1);
emp.LastName = reader.GetString(2);
}
reader.Close();
cnn.Close();
return emp;
}
It accepts EmployeeID a one of its parameters. The code is similar to the previous code but returns only one employee.
[WebMethod] public int Insert(string pFirstName, string pLastName)
{
SqlConnection cnn = new SqlConnection(strConn);
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "insert into employees(firstname,lastname)values (@fname,@lname)";
SqlParameter fname = new SqlParameter("@fname", pFirstName);
SqlParameter lname = new SqlParameter("@lname", pLastName);
cmd.Parameters.Add(fname);
cmd.Parameters.Add(lname);
int i = cmd.ExecuteNonQuery();
cnn.Close();
return i;
}
[WebMethod] public int Update(int pEmployeeId,string pFirstName, string pLastName)
{
SqlConnection cnn = new SqlConnection(strConn);
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "update employees set firstname=@fname, lastname=@lname where employeeid=@id";
SqlParameter fname = new SqlParameter("@fname", pFirstName);
SqlParameter lname = new SqlParameter("@lname", pLastName);
SqlParameter id = new SqlParameter("@id", pEmployeeId);
cmd.Parameters.Add(fname);
cmd.Parameters.Add(lname);
cmd.Parameters.Add(id);
int i = cmd.ExecuteNonQuery();
cnn.Close();
return i;
}
[WebMethod] public int Delete(int pEmployeeId)
{
SqlConnection cnn = new SqlConnection(strConn);
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "delete from employees where employeeid=@id";
SqlParameter id = new SqlParameter("@id", pEmployeeId);
cmd.Parameters.Add(id);
int i = cmd.ExecuteNonQuery();
cnn.Close();
return i;
}
The Insert() web method accepts the first name and last name of the employee to be added. It then creates a SqlConnection and SqlCommand object and executes the INSERT statement using the ExecuteNonQuery() method of the SqlCommand object. Similarly, the Update() web method accepts the employee ID to be updated, along with new values for first name and last name, and fires an UPDATE statement. Finally, the Delete() web method accepts an employee ID that is to be deleted and fires a DELETE statement.
8.) Uptil now we haven't implimented anything of AJAX. To impliment it modify your class definition as follows
using System.Web.Script.Services; ...
...
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class EmployeeService : System.Web.Services.WebService
{
...
...
System.Web.Script.Services is a namespace imported from System.Web.Extension which is required for using [ScriptService] attribute.
The [ScriptService] attribute enables the web service to be called from the client-side JavaScript.
Using The Web Service
1. Add a new web form EmployeeClient.aspx. 2. Open the toolbox by using View->Toolbox. On the toolbox menu locate AJAX Extension. It Displays the various components of AJAX toolkit that can be used in the web form.
3. Drag and drop "Script Manager" on the web form. Every web form requires one script manager. 4. Locate its Services property and open the Service Reference collection editor. Click the Add button at the bottom of the dialog and set the Path property to the path of the web service (in other words, EmployeeService.asmx).
5. Now design the web form with the following markup in your code file
Notice that we do not need asp controls instead we are using simple HTML controls.
This is because you want to call your web service from client-side JavaScript and not from server-side code.
6. Now, create a <script> tag in the <head> elemant. And add the following method
function CallWebMethod(methodType)
{
switch(methodType)
{
case "select":
EmployeeService.GetEmployees(FillEmployeeList, ErrorHandler, TimeOutHandler);
break;
case "selectone":
var select=document.getElementById("Select1");
var empid=select.options[select.selectedIndex].value;
EmployeeService.GetEmployee(empid,DisplayEmployeeDetails, ErrorHandler,TimeOutHandler);
break;
case "insert":
var text1=document.getElementById("Text1");
var text2=document.getElementById("Text2");
EmployeeService.Insert(text1.value,text2.value, InsertEmployee,ErrorHandler, TimeOutHandler);
break;
case "update":
var select=document.getElementById("Select1");
var empid=select.options[select.selectedIndex].value;
var text1=document.getElementById("Text1");
var text2=document.getElementById("Text2");
var emp=new Employee();
emp.EmployeeID=empid;
emp.FirstName=text1.value;
emp.LastName=text2.value;
EmployeeService.Update(empid,text1.value,text2.value, UpdateEmployee,ErrorHandler, TimeOutHandler);
break;
case "delete":
var select=document.getElementById("Select1");
var empid=select.options[select.selectedIndex].value;
EmployeeService.Delete(empid,DeleteEmployee,ErrorHandler, TimeOutHandler);
break;
}
}
The CallWebMethod() function is the main function that makes calls to the web service. The function accepts a string parameter indicating the method to be called. It contains a switch statement that checks the method to be called. Each case block calls one web method. The ASP.NET AJAX framework automatically creates a JavaScript proxy class for the web service. The proxy class has the same name as the web service. So, the EmployeeService in the above code is not the actual web service class but a JavaScript proxy class. The proxy contains all the web methods of the original web service. In addition to the original web method parameters, each method can have three extra parameters.
7. Now add the function declaration that were declared in the above CallWebMethod()
function FillEmployeeList(result)
{
var select=document.getElementById("Select1");
for(var i=0;i<result.length;i++)
{
var option=new Option(result[i].EmployeeID, result[i].EmployeeID);
select.options.add(option);
}
}
function DisplayEmployeeDetails(result)
{
var text1=document.getElementById("Text1");
var text2=document.getElementById("Text2");
text1.innerText=result.FirstName;
text2.innerText=result.LastName;
var lblMsg=document.getElementById("lblMsg");
lblMsg.innerText="";
}
function InsertEmployee(result)
{
if(result>0)
{
var lblMsg=document.getElementById("lblMsg");
lblMsg.innerText="Employee added successfully!";
}
else
{
var lblMsg=document.getElementById("lblMsg");
lblMsg.innerText="Error occurred while adding new employee!";
}
}
function UpdateEmployee(result)
{
if(result>0)
{
var lblMsg=document.getElementById("lblMsg");
lblMsg.innerText="Employee updated successfully!";
}
else
{
var lblMsg=document.getElementById("lblMsg");
lblMsg.innerText="Error occurred while updating the employee!";
}
}
function DeleteEmployee(result)
{
if(result>0)
{
var lblMsg=document.getElementById("lblMsg");
lblMsg.innerText="Employee deleted successfully!";
}
else
{
var lblMsg=document.getElementById("lblMsg");
lblMsg.innerText="Error occurred while deleting employee!";
}
}
8. Notice that in Step 6 the first case of "select", this is called to populate the drop down list when the page loads or else an error will be displayed. The definition of the function is given below
function pageLoad()
{
CallWebMethod("select");
}
The error handler and timeouthandler functions are defined as
function ErrorHandler(result)
{
var msg=result.get_exceptionType() + "\r\n";
msg += result.get_message() + "\r\n";
msg += result.get_stackTrace();
alert(msg);
}
function TimeOutHandler(result)
{
alert("Timeout :" + result);
}
These two methods show an alert to the user whenever an error has occured or a user has been timed out by the server. The result parameter received by this method provides three methods: get_exceptionType(), get_message(), and get_stackTrace().
Testing The Web Page
Now everything is in position all that remains is to run the code.
If any error occurs go through the process again.