AJAX with ASP.NET using Visual Studio 2005 and AJAX Toolkit
User Rating: / 3
PoorBest 
Written by Deepesh   







ajax_visual_studio_img_intro.jpg

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.
  • ajax_visual_studio_img1.png


    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:

    <add name=" Connstr" connectionString="server=YourServer;uid=YourUID;
    pwd=YourPassword;database=Northwind" providerName="System.Data.SqlClient" />

    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.

    private string strConn = "";
    public EmployeeService()
    {
       strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
    }


    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.

    Ajax Toolbox 

     

    ajax_visual_studio_img3.png 


    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

    ajax_visual_studio_img4.png 

     

    <table>
       <tr>
          <td colspan="2">
             <asp:Label ID="Label4" runat="server" Font-Size="X-Large" Text="Employee Management">
             </asp:Label></td>
       </tr>
       <tr>
          <td style="width: 100px">
             <asp:Label ID="Label1" runat="server" Text="Employee ID :"></asp:Label></td>
          <td style="width: 100px">
             <select id="Select1" >
             </select>
          </td>
       </tr>
       <tr>
          <td style="width: 100px">
             <asp:Label ID="Label2" runat="server" Text="First Name :"></asp:Label></td>
          <td style="width: 100px">
             <input id="Text1" type="text" /></td>
       </tr>
       <tr>
          <td style="width: 100px">
             <asp:Label ID="Label3" runat="server" Text="Last Name :"></asp:Label></td>
          <td style="width: 100px">
             <input id="Text2" type="text" /></td>
       </tr>
       <tr>
          <td align="center" colspan="2">
             <input id="Button3" type="button" value="Insert" />
             <input id="Button4" type="button" value="Update" />
             <input id="Button5" type="button" value="Delete" />
          </td>
       </tr>
       <tr>
          <td align="center" colspan="2">
             <span id="lblMsg" style="font-weight: bold; color: red;"></span>
          </td>
       </tr>
    </table>

    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

    ajax_visual_studio_img5.png

    Now everything is in position all that remains is to run the code.
    If any error occurs go through the process again.  

     

     

    ajax_visual_studio_img_intro.jpg





     

    Quote this article on your site

      Comments (4)
     1 Written by bandi, on 16-05-2008 12:02
    hi this is very nice :p
     2 Comment 04 1648
    Written by This e-mail address is being protected from spam bots, you need JavaScript enabled to view it , on 04-07-2008 21:47
    Hielloo , pcc pueblo community college, "slutty hot moms" "college sluts" "teen sluts", myspcace college football layouts, grants for college students with disabilities, college girl big tit fuck, amateur busty brunette college girl strip and posing, weber state college football history, cute nude college girls student, lansing community college web site, santa clara college basketball tickets, johnson county community college cavalier, college essays on majors, free college girls sex pics, montgomery community college rockville, queens college charlotte
     3 Comment 04 2324
    Written by This e-mail address is being protected from spam bots, you need JavaScript enabled to view it , on 05-07-2008 04:24
    Hielloo , boston college eagles tom o.27brien era, home building loan savings bank, flight status for british airways, get a loan for debitswith bad credit and no home, virgi blue flight information, flight tickets cheap, free international flight tracker, the student loan corporation, best on line college law degree consumer reports, bad credit loan online, instant unsecured loan no credit check, lake city community college, free pictures naked college girls, daley flight 29 down, how to get the student loan for the college
     4 Comment 05 1717
    Written by This e-mail address is being protected from spam bots, you need JavaScript enabled to view it , on 05-07-2008 22:16
    Hielloo , babies r us printable coupons, coupons las vegas, airline ticket las vegas, ticket office skybus airline, airline ticket prices all countrys, airline blue jet ticket, hongkong airline ticket, airline ticket to italy, payless shoe store coupons, lillian vernon online coupons, need loan for airline ticket, wholesale airline ticket, coupons or promotional codes, cheap ticket from turkish airline

    Write Comment
    • Please keep the topic of messages relevant to the subject of the article.
    • Personal verbal attacks will be deleted.
    • Please don't use comments to plug your web site. Such material will be removed.
    • Just ensure to *Refresh* your browser for a new security code to be displayed prior to clicking on the 'Send' button.
    • Keep in mind that the above process only applies if you simply entered the wrong security code.
    Name:
    E-mail
    Homepage
    Title:
    BBCode:Web AddressEmail AddressBold TextItalic TextUnderlined TextQuoteCodeOpen ListList ItemClose List
    Comment:



    Code:* Code
    I wish to be contacted by email regarding additional comments


    Powered by AkoComment Tweaked Special Edition v.1.4.6
    AkoComment © Copyright 2004 by Arthur Konze - www.mamboportal.com. All right reserved

     
    < Prev   Next >




    Privacy Notice | Advertising Info | Feedback | Contact Us | Partners

    The information and views presented above are by the author. Mabaloo.com does not take any gurantee of accuracy.
    The views expressed above are that of the author and in no way related to mabaloo.com

    © 2007 @ mabaloo.com.